UIScrollView小练手


// ViewController.h
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController


@end

// ViewController.m
#import "ViewController.h"
#import "UIView+LZExtension.h"
#import "UIView+Extension.h"
#import "UIView+Addition.h"
#import "XMDTools.h"

#define MainWidth [UIScreen mainScreen].bounds.size.width
#define MainHeight [UIScreen mainScreen].bounds.size.height
#define kWidthPerHoursView (MainWidth/5)
#define kHeightHoursScrollView 84
#define kTagHoursStatus 100
#define kTagHoursTime 200
#define kTagHoursHeart 300
#define kTagHoursBtn 400

// rgb颜色转换(16进制->10进制)
#define HexColor(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

@interface ViewController () <UIScrollViewDelegate>

@property (nonatomic, strong) UIScrollView* mHourScrollView;
/** 按钮 */
@property (nonatomic, strong) UIButton *addBtn;
/** 可变数组 */
@property (nonatomic, strong) NSMutableArray *dataArray;

@end

@implementation ViewController

#pragma mark - 懒加载
-(UIScrollView*)mHourScrollView{
    if (_mHourScrollView == nil) {
        // 创建对象,高度84
        _mHourScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 100, MainWidth, kHeightHoursScrollView)];
        _mHourScrollView.delegate = self;
        _mHourScrollView.scrollEnabled = YES;
        _mHourScrollView.clipsToBounds = YES;
        [_mHourScrollView setCanCancelContentTouches:NO];
        _mHourScrollView.backgroundColor = [UIColor blueColor];
        _mHourScrollView.showsHorizontalScrollIndicator = NO;
        _mHourScrollView.showsVerticalScrollIndicator = NO;
    }
    return _mHourScrollView;
}

- (UIButton*)addBtn{
    if (_addBtn == nil) {
        _addBtn = [[UIButton alloc] init];
        _addBtn.frame = CGRectMake(0, MainHeight - 60, MainWidth, 60);
        [_addBtn setTitle:@"点我" forState:UIControlStateNormal];
        _addBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
        [_addBtn addTarget:self action:@selector(add) forControlEvents:UIControlEventTouchUpInside];
        _addBtn.backgroundColor = [UIColor redColor];
    }
    return _addBtn;
}

- (NSMutableArray*)dataArray{
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

/*
    实现思路:
    1.创建一个宽度和屏幕宽度等宽的UIScrollView对象
    2.给mHourScrollView添加视图,注意点是:第一个添加的视图距离左边2个间隔,mHourScrollView的contentSize
       是添加的子视图的个数+4
 */
- (void)viewDidLoad {
    [super viewDidLoad];
    // 添加
    [self.view addSubview:self.mHourScrollView];
    [self.view addSubview:self.addBtn];
}

#pragma mark - 事件
- (void)add {
    // 拿到今天的日期
    NSDate* date = [NSDate date];
    // 日期转时间
    NSString* dateString = [XMDTools stringWithDate:date byType:date_type_HM];
//    NSLog(@"dateString==%@", dateString); // dateString==17:15
    NSString *newStr = [dateString substringToIndex:2];

    // 转化成整形数值
    int newValue = [newStr intValue];

    NSString *dateStr = nil;

    if (newValue % 2 == 0) { // 偶数
        dateStr = [NSString stringWithFormat:@"%@:00", newStr];
    } else {
        newValue = newValue - 1;
        dateStr = [NSString stringWithFormat:@"%02zd:00", newValue];
    }

    // 添加
    [self.dataArray addObject:dateStr];
    // 给mHourScrollView添加视图
    [self addHoursView:_mHourScrollView];
}

// 给mHourScrollView添加视图
-(void)addHoursView:(UIScrollView*)scrollView{

    for (UIView *view in _mHourScrollView.subviews) {
        [view removeFromSuperview];
    }

    // 设置距离左边开始的间隔
    float left = 2 * kWidthPerHoursView;
    for (int i = 0; i < self.dataArray.count; i++) {
        //创建按钮
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        // 设置frame
        btn.frame = CGRectMake(left, 0, kWidthPerHoursView, kHeightHoursScrollView);
        // 设置标记
        btn.tag = kTagHoursBtn + i;
        // 添加监听事件
        [btn addTarget:self action:@selector(onClickHoursBtn:) forControlEvents:UIControlEventTouchUpInside];
        // 添加按钮
        [scrollView addSubview:btn];

        [btn setBackgroundColor:[UIColor greenColor]];

        // 拿到图片
        UIImage* sunImg = [UIImage imageNamed:@"sun_icon"];
        UIImage* moonImg = [UIImage imageNamed:@"moon_icon"];
        UIImageView* imgView = [[UIImageView alloc] init];

        if (i < 3 || i > 9) {
            imgView.image = moonImg;
        }else{
            imgView.image = sunImg;
        }
        imgView.tag = kTagHoursStatus + i;
        [btn addSubview:imgView];
        // 创建UILabel对象
        UILabel* timeLabel = [[UILabel alloc] init];
        // 设置内容
        timeLabel.text = self.dataArray[i];
        timeLabel.tag = kTagHoursTime + i;
        timeLabel.font = [UIFont systemFontOfSize:16.];
        timeLabel.textColor = HexColor(0x80593e);
        [btn addSubview:timeLabel];
        // 创建心率label
        UILabel* heartLabel = [[UILabel alloc] init];
        heartLabel.tag = kTagHoursHeart + i;
        heartLabel.font = [UIFont boldSystemFontOfSize:22];
        heartLabel.textAlignment = NSTextAlignmentCenter;
        heartLabel.textColor = HexColor(0x80593e);
        [btn addSubview:heartLabel];
        // 获得尺寸
        CGSize timeSize = [timeLabel.text sizeWithAttributes:@{NSFontAttributeName:timeLabel.font}];
        float imgViewX = (kWidthPerHoursView - imgView.image.size.width - 3 - timeSize.width)/2;
        imgView.frame = CGRectMake(imgViewX, 14, imgView.image.size.width, imgView.image.size.height);
        timeLabel.frame = CGRectMake(imgView.maxX + 3, imgView.top + (imgView.height - timeSize.height)/2, timeSize.width, timeSize.height);
        heartLabel.frame = CGRectMake(0, kHeightHoursScrollView/2, kWidthPerHoursView, kHeightHoursScrollView/2);

        imgView.backgroundColor = [UIColor purpleColor];
        timeLabel.backgroundColor = [UIColor greenColor];
        heartLabel.backgroundColor = [UIColor orangeColor];

        left += kWidthPerHoursView;
    }
    _mHourScrollView.contentSize = CGSizeMake((self.dataArray.count + 4)* kWidthPerHoursView, 0);
}

-(void)onClickHoursBtn:(UIButton*)btn{
    // 拿到下标0---12
    int index = (int)(btn.tag - kTagHoursBtn);
    // 设置偏移量
    [self.mHourScrollView setContentOffset:CGPointMake((index) * kWidthPerHoursView, 0) animated:YES];
}

/**
 *  用户已经停止拖拽scrollView时,就会调用这个方法
 */
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if(decelerate == NO) {
        if (scrollView == self.mHourScrollView) {
            int index = ((self.mHourScrollView.contentOffset.x + kWidthPerHoursView/2) / kWidthPerHoursView);
            [self changeHoursScrollViewSelectIndex:index];
        }
    }
}

/**
 *  减速完毕的时候会调用这个方法(停止滚动)
 */
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView == self.mHourScrollView) {
        int index = ((self.mHourScrollView.contentOffset.x + kWidthPerHoursView/2) / kWidthPerHoursView);
        [self changeHoursScrollViewSelectIndex:index];
    }
}

/**
 *  改变小时时间线的scrollView的下标
 */
- (void)changeHoursScrollViewSelectIndex : (int)index {
    [self.mHourScrollView setContentOffset:CGPointMake(index * kWidthPerHoursView, 0) animated:YES];
}

@end


  • 运行效果:

推荐阅读更多精彩内容