現在的App中,圖片輪播器是再常見的不過的一種UI交互方式了。今天這邊就給大家寫一個用scrollview完成的圖片輪播器。
先來看下效果:
其實即使是IOS的初學者,讓圖片滾動起來并不是難題,而這邊圖片輪播的難點在于一個圖片周期的循環,也就是在最后一張跳入第一張的(或者最后一張跳入第一張)時的動畫問題。
以下提供實現思路:
頁面上只需要一個scrollView,在ScrollView上添置左中右各三個UIImageVIew
當圖片停止時,此時左中右圖片分別為 圖1 圖2 圖3,
當前scrollView的始終停留在Center ImageView上。
當向右滑動時,scrollView最終停留在RightImageView(即圖2)上時,
在- (void)scrollViewDidEndDecelerating:(UIScrollView*)scrollView方法中
刷新三個ImageView的圖片,此時左中右三張圖片分別為圖2 圖3 圖4
同時將scrollView移動回中間Center;
注意:刷新三個ImageView和scrollView的操作是同時進行的。并且scrollView移動的過程中 用到- (void)setContentOffset:(CGPoint)contentOffset animated:(BOOL)animated;方法時,需要將動畫效果設置為NO;
此時在用戶看來,就是手機屏幕中從圖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]];
}
對應這個案列,我使用了3個全局變量Index來記錄三張ImageView的圖片
@property(nonatomic,assign)NSUIntegercurrentImageIndex;
@property(nonatomic,assign)NSIntegerleftImageIndex;
@property(nonatomic,assign)NSIntegerrightImageIndex;
剛才提到的最后一張圖和第一張圖的動畫,可以在Index上的判斷來實現
- (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;
? ? ? ? ?}
}
最后加上了一些簡單的封裝和定時器效果
附上GitHub鏈接:GitHub - DerrickQin2853/SimplePictureCarouselScrollView: A Demo PictureCarousel using scrollView
如有問題,歡迎各位指出討論。感謝閱讀