現(xiàn)在的App中,圖片輪播器是再常見的不過的一種UI交互方式了。今天這邊就給大家寫一個(gè)用scrollview完成的圖片輪播器。
先來看下效果:

其實(shí)即使是IOS的初學(xué)者,讓圖片滾動起來并不是難題,而這邊圖片輪播的難點(diǎn)在于一個(gè)圖片周期的循環(huán),也就是在最后一張?zhí)氲谝粡埖模ɑ蛘咦詈笠粡執(zhí)氲谝粡垼r(shí)的動畫問題。
以下提供實(shí)現(xiàn)思路:
頁面上只需要一個(gè)scrollView,在ScrollView上添置左中右各三個(gè)UIImageVIew

當(dāng)圖片停止時(shí),此時(shí)左中右圖片分別為 圖1 圖2 圖3,
當(dāng)前scrollView的始終停留在Center ImageView上。
當(dāng)向右滑動時(shí),scrollView最終停留在RightImageView(即圖2)上時(shí),
在- (void)scrollViewDidEndDecelerating:(UIScrollView*)scrollView方法中
刷新三個(gè)ImageView的圖片,此時(shí)左中右三張圖片分別為圖2 圖3 圖4
同時(shí)將scrollView移動回中間Center;
注意:刷新三個(gè)ImageView和scrollView的操作是同時(shí)進(jìn)行的。并且scrollView移動的過程中 用到- (void)setContentOffset:(CGPoint)contentOffset animated:(BOOL)animated;方法時(shí),需要將動畫效果設(shè)置為NO;
此時(shí)在用戶看來,就是手機(jī)屏幕中從圖1過渡到圖2的動畫過程。
代碼:
- (void)scrollViewDidEndDecelerating:(UIScrollView*)scrollView {
?[self reloadImageViews];
?[_mainScrollView ? ? ? ? ? ? ? ?setContentOffset:CGPointMake(_mainScrollView.bounds.size.width,0) animated:NO];?
}
- (void)reloadImageViews {
? ? ? ? ? CGPointscrollViewOffset = [_mainScrollViewcontentOffset];
? ? ? ? ? if(scrollViewOffset.x==2*_mainScrollView.bounds.size.width) {
? ? ? ? ? [selfcurrentImageIndexAdd];
? ? }elseif(scrollViewOffset.x==0) {
? ? ? ? ?[selfcurrentImageIndexMinus];
? ? }
?_centerImageView.image= ? ? ? ? ? ? ? [UIImageimageNamed:_picDataArray[self.currentImageIndex]];
_leftImageView.image= [UIImageimageNamed:_picDataArray[self.leftImageIndex]];
_rightImageView.image =[UIImageimageNamed:_picDataArray[self.rightImageIndex]];
}
對應(yīng)這個(gè)案列,我使用了3個(gè)全局變量Index來記錄三張ImageView的圖片
@property(nonatomic,assign)NSUIntegercurrentImageIndex;
@property(nonatomic,assign)NSIntegerleftImageIndex;
@property(nonatomic,assign)NSIntegerrightImageIndex;
剛才提到的最后一張圖和第一張圖的動畫,可以在Index上的判斷來實(shí)現(xiàn)
- (NSInteger)leftImageIndex {
? ? ?if(_currentImageIndex==0) {
? ? ? ? ? ?_leftImageIndex=kImageCount-1;
? ? ? }else{
? ? ? ? ? ?_leftImageIndex=_currentImageIndex-1;
? }
? ? ?return_leftImageIndex;
}
- (NSInteger)rightImageIndex {
? ? ? ? ?if(_currentImageIndex==kImageCount-1) {
? ? ? ? ? ? _rightImageIndex=0;
? ? ? ? ? }else{
? ? ? ? ? ? _rightImageIndex=_currentImageIndex+1;
? ? ? ? ? }
? ? ? ?return_rightImageIndex;
}
- (void)currentImageIndexAdd {
? ? ? ? ?if(self.currentImageIndex==kImageCount-1) {
? ? ? ? ? ? ? ? ?self.currentImageIndex=0;
? ? ? ? ? }else{
? ? ? ? ? ? ? ? ? self.currentImageIndex=self.currentImageIndex+1;
? ? ? ? ? }
? ? }
- (void)currentImageIndexMinus {
? ? ? ? ?if(self.currentImageIndex==0) {
? ? ? ? ? ? ? ? self.currentImageIndex=kImageCount-1;
? ? ? ? ? }else{
? ? ? ? ? ? ? ? self.currentImageIndex=self.currentImageIndex-1;
? ? ? ? ?}
}
最后加上了一些簡單的封裝和定時(shí)器效果
附上GitHub鏈接:GitHub - DerrickQin2853/SimplePictureCarouselScrollView: A Demo PictureCarousel using scrollView
如有問題,歡迎各位指出討論。感謝閱讀