直接上代碼 粘貼即可以用
@property(nonatomic,strong)UIScrollView *scrollview;
@property(nonatomic,strong)UIPageControl * pageControl;
@property (nonatomic, strong) NSTimer *timer;
@property(nonatomic,strong)UIImageView * scrollImage;
self.scrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-myWebView.frame.size.height-100, self.view.frame.size.width, 100)];
self.scrollview.delegate = self;
self.scrollview.showsHorizontalScrollIndicator = NO;
self.scrollview.shouldGroupAccessibilityChildren = NO;
self.scrollview.pagingEnabled = YES;
[self.view addSubview:self.scrollview];
self.pageControl =[[UIPageControl alloc]init];
self.pageControl.numberOfPages = 3;
self.pageControl.currentPageIndicatorTintColor = [UIColor clearColor];
self.pageControl.pageIndicatorTintColor = [UIColor clearColor];
[self.view addSubview:self.pageControl];
[self.pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
make.centerX.equalTo(self.scrollview.mas_centerX);
make.centerY.equalTo(self.scrollview.mas_centerY).with.offset(30);
make.height.mas_equalTo(15);
make.width.mas_equalTo(30);
}];
//? ? 圖片的寬
CGFloat imageW = self.scrollview.frame.size.width;
//? ? 圖片高
CGFloat imageH = self.scrollview.frame.size.height;
//? ? 圖片的Y
CGFloat imageY = 0;
//? ? 圖片中數(shù)
NSInteger totalCount = 3;
for (int i = 0; i < totalCount; i++) {
self.scrollImage= [[UIImageView alloc] init];
//? ? ? ? 圖片X
CGFloat imageX = i * imageW;
//? ? ? ? 設(shè)置frame
self.scrollImage.frame = CGRectMake(imageX, imageY, imageW, imageH);
//? ? ? ? 設(shè)置圖片
self.scrollImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"image%d", i + 1]];
//? ? ? 隱藏指示條
self.scrollview.showsHorizontalScrollIndicator = NO;
[self.scrollview addSubview:self.scrollImage];
}
// 設(shè)置scrollview的滾動范圍
CGFloat contentW = totalCount *imageW;
//不允許在垂直方向上進行滾動
self.scrollview.contentSize = CGSizeMake(contentW, 0);
//? ? 3.設(shè)置分頁
self.scrollview.pagingEnabled = YES;
//? ? 4.監(jiān)聽scrollview的滾動
self.scrollview.delegate = self;
[self addTimer];
// scrollview滾動的時候調(diào)用
- (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{
//? ? 關(guān)閉定時器(注意點; 定時器一旦被關(guān)閉,無法再開啟)
[self removeTimer];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
//? ? 開啟定時器
[self addTimer];
}
-(void)addTimer{
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.5 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];
}