博客> scrollView,pageControll和NSTimer
scrollView,pageControll和NSTimer
2017-08-15 05:58 评论:0 阅读:296 OS_JJ
ios 获取当前日期
调用<UIScrollViewDelegate>

创建相关成员变量
{
    NSArray *_dataArr;
}
@property(nonatomic,strong)UIScrollView *scrollView;
@property(nonatomic,strong)NSTimer *timer;
@property(nonatomic,strong)UIPageControl *page;

初始化

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //初始化图片数组
    _dataArr = @[@"img_01",@"img_02",@"img_03",@"img_04",@"img_05"];
    [self createKit];

}

- (void)createKit{
    //创建scrollView
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(10, 30, WIDTH-20, 130)];
    self.scrollView.pagingEnabled = YES;
    self.scrollView.delegate = self;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.scrollView];
    self.scrollView.contentSize = CGSizeMake((WIDTH-20) * _dataArr.count, 0);

    //创建imageView
    for (int i = 0; i < _dataArr.count; i++) {
        UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake((WIDTH -20)* i , 0, WIDTH-20, 130)];
        image.image = [UIImage imageNamed:_dataArr[i]];
        [self.scrollView addSubview:image];
    }

    //创建pageControl
    self.page = [[UIPageControl alloc]initWithFrame:CGRectMake(WIDTH/2-100, 135, 200, 25)];
    self.page.currentPageIndicatorTintColor = [UIColor redColor];
    self.page.pageIndicatorTintColor = [UIColor blueColor];
    self.page.numberOfPages = _dataArr.count;
    [self.page addTarget:self action:@selector(pageChange) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.page];

    //创建定时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(imageChange) userInfo:nil repeats:YES];

    //防止其他scrollView相关冲突
    [[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)pageChange{
    self.scrollView.contentOffset = CGPointMake(self.page.currentPage * (WIDTH - 20), 0);

}

//定时器实现方法
- (void)imageChange{
    long int scrollPage = 0;
    if (self.page.currentPage == _dataArr.count - 1) {
        scrollPage = 0;
    }else{

       scrollPage = self.page.currentPage + 1;
    }

    [self.scrollView setContentOffset:CGPointMake(scrollPage * (WIDTH-20),0) animated:YES];

}

//分页实现
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.page setCurrentPage:(scrollView.contentOffset.x + (WIDTH-20)*0.5)/(WIDTH-20)];

}

//不拖拽时开启定时器
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(imageChange) userInfo:nil repeats:YES];
}

//拖拽时停止定时器
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{

    [self.timer invalidate];
    self.timer = nil;

}
收藏
0
sina weixin mail 回到顶部