代码拿去 拿去修修改改 就是属于你的了
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 150)];
scrollView.delegate = self;
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.shouldGroupAccessibilityChildren = NO;
scrollView.pagingEnabled = YES;
self.scrollview = scrollView;
[headerView addSubview:scrollView];
UIPageControl * pagecontrol =[[UIPageControl alloc]init];
pagecontrol.numberOfPages = 3;
pagecontrol.currentPageIndicatorTintColor = [UIColor blueColor];
pagecontrol.pageIndicatorTintColor = [UIColor yellowColor];
self.pageControl = pagecontrol;
[headerView addSubview:pagecontrol];
[pagecontrol mas_makeConstraints:^(MASConstraintMaker *make) {
make.centerX.equalTo(scrollView.mas_centerX);
make.centerY.equalTo(scrollView.mas_centerY).with.offset(50);
make.height.mas_equalTo(15);
make.width.mas_equalTo(30);
}];
// 图片的宽
CGFloat imageW = scrollView.frame.size.width;
// 图片高
CGFloat imageH = scrollView.frame.size.height;
// 图片的Y
CGFloat imageY = 0;
// 图片中数
NSInteger totalCount = 3;
for (int i = 0; i < totalCount; i++) {
UIImageView *imageView = [[UIImageView alloc] init];
// 图片X
CGFloat imageX = i * imageW;
// 设置frame
imageView.frame = CGRectMake(imageX, imageY, imageW, imageH);
// 设置图片
imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"image%d", i + 1]];
// 隐藏指示条
scrollView.showsHorizontalScrollIndicator = NO;
[self.scrollview addSubview:imageView];
}
// 设置scrollview的滚动范围
CGFloat contentW = totalCount *imageW;
//不允许在垂直方向上进行滚动
scrollView.contentSize = CGSizeMake(contentW, 0);
// 3.设置分页
scrollView.pagingEnabled = YES;
// 4.监听scrollview的滚动
scrollView.delegate = self;
[self addTimer];
// scrollview滚动的时候调用
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
// 计算页码
CGFloat scrollviewW = scrollView.frame.size.width;
CGFloat x = scrollView.contentOffset.x;
int page = (x + scrollviewW / 2) / scrollviewW;
self.pageControl.currentPage = page;
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
// 关闭定时器(注意点; 定时器一旦被关闭,无法再开启)
[self removeTimer];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
// 开启定时器
[self addTimer];
}
-(void)addTimer{
self.timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
}
- (void)nextImage{
int page = (int)self.pageControl.currentPage;
if (page == 2) {
page = 0;
}else
{
page++;
}
// 滚动scrollview
CGFloat x = page * self.scrollview.frame.size.width;
self.scrollview.contentOffset = CGPointMake(x, 0);
}
- (void)removeTimer{
[self.timer invalidate];
}