iOS自動輪播器代碼

代碼拿去 拿去修修改改 就是屬于你的了

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];

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容