代碼拿去 拿去修修改改 就是屬于你的了
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;
//? ? 圖片中數(shù)
NSInteger totalCount = 3;
for (int i = 0; i < totalCount; i++) {
UIImageView *imageView = [[UIImageView alloc] init];
//? ? ? ? 圖片X
CGFloat imageX = i * imageW;
//? ? ? ? 設(shè)置frame
imageView.frame = CGRectMake(imageX, imageY, imageW, imageH);
//? ? ? ? 設(shè)置圖片
imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"image%d", i + 1]];
//? ? ? 隱藏指示條
scrollView.showsHorizontalScrollIndicator = NO;
[self.scrollview addSubview:imageView];
}
// 設(shè)置scrollview的滾動(dòng)范圍
CGFloat contentW = totalCount *imageW;
//不允許在垂直方向上進(jìn)行滾動(dòng)
scrollView.contentSize = CGSizeMake(contentW, 0);
//? ? 3.設(shè)置分頁(yè)
scrollView.pagingEnabled = YES;
//? ? 4.監(jiān)聽(tīng)scrollview的滾動(dòng)
scrollView.delegate = self;
[self addTimer];
// scrollview滾動(dòng)的時(shí)候調(diào)用
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//? ? 計(jì)算頁(yè)碼
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{
//? ? 關(guān)閉定時(shí)器(注意點(diǎn); 定時(shí)器一旦被關(guān)閉,無(wú)法再開(kāi)啟)
[self removeTimer];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
//? ? 開(kāi)啟定時(shí)器
[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++;
}
//? 滾動(dòng)scrollview
CGFloat x = page * self.scrollview.frame.size.width;
self.scrollview.contentOffset = CGPointMake(x, 0);
}
- (void)removeTimer{
[self.timer invalidate];
}