專案中經常會遇到「多張圖片無限循環輪轉」的需求。以前做過,好幾個地方都用到了,當時沒有封裝,幾個地方都複製了幾乎一樣的程式碼,複用性很差。今天沒事就把它封裝了一下,使用起來比較簡單。
先說說實現循環輪轉圖片的思想:在 UIScrollView 中添加 3 個並排排列的 UIImageView,我們看到的永遠只是第二個 UIImageView。這樣一來,你可以一直向左、向右滑動;當向左滑到最後一個 UIImageView 無法再滑動時,我在背後悄悄地把第二個 UIImageView 的圖片設為當前要顯示的圖片,並調整 UIScrollView 的 contentOffset:
[_contentScrollView setContentOffset:CGPointMake(self.bounds.size.width, 0) animated:NO]
使用者根本感覺不出這種變化,此時你看到的又是第二個 UIImageView,於是又能繼續向左滑動;向右滑動時處理類似。如此一來就能實現左右無限循環輪轉圖片。
JGCirculateSwitchImgView.h 頭文件
@interface JGCirculateSwitchImgView : UIView @property(nonatomic,strong)NSArray *imgUrlArr; @end
頭文件中只有一個需要設定的成員變量 imgUrlArr 數組,就是要顯示的圖片路徑數組,會透過這個數組載入圖片。
JGCirculateSwitchImgView.m 文件
typedef NS_ENUM(NSInteger, SwitchDirection) {
//未成功旋轉
SwitchDirectionNone = -1,
//向右旋轉圖片
SwitchDirectionRight = 0,
//向左旋轉圖片
SwitchDirectionLeft = 1,
};
定義了 SwitchDirection 枚舉,表示圖片向左、向右輪轉,或者什麼也不做。
//預設5秒旋轉圖片一次,可以根據需要改變 #define WiatForSwitchImgMaxTime 5 #import "JGCirculateSwitchImgView.h" #import "UIImageView+WebCache.h" @interface JGCirculateSwitchImgView () //底部 UIScrollView @property(nonatomic,weak)UIScrollView *contentScrollView; //顯示頁碼的 UIPageControl 控件 @property(nonatomic,weak)UIPageControl *pageControlView; //用保存當前 UIPageControl 控件顯示的當前位置 @property(nonatomic,assign)NSInteger currentPage; //用於保存當前顯示圖片在圖片 urlArr 數組中的索引 @property(nonatomic,assign)NSInteger currentImgIndex; //UIScrollView 上的三個 UIImageView,這裡通過 3 個 UIImageView 實現無限循環圖片輪轉 @property(nonatomic,weak)UIImageView *imgView1; @property(nonatomic,weak)UIImageView *imgView2; @property(nonatomic,weak)UIImageView *imgView3; @property(nonatomic,assign)BOOL isDragImgView; //SwitchDirection 類型,用於保存滑動的方向 @property(nonatomic,assign)SwitchDirection swDirection; @end
-(id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
[self createContentScrollView];
[self createPageControlView];
//預設第一頁
_currentPage = 0;
//預設顯示第一張圖片
_currentImgIndex = 0;
_isDragImgView = NO;
_swDirection = SwitchDirectionNone;
}
return self;
}
創建 UIScrollView 代碼
-(void)createContentScrollView {
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
scrollView.delegate = self;
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.shouldGroupAccessibilityChildren = NO;
scrollView.pagingEnabled = YES;
[self addSubview:scrollView];
_contentScrollView = scrollView;
}
創建 UIPageControl
-(void)createPageControlView {
UIPageControl *pageControlVw = [[UIPageControl alloc] init];
pageControlVw.frame = CGRectMake(0, 0, 80, 20);
pageControlVw.center = CGPointMake(self.center.x, self.bounds.size.height - 20);
pageControlVw.backgroundColor = [UIColor redColor];
_pageControlView.pageIndicatorTintColor = [UIColor yellowColor];
_pageControlView.currentPageIndicatorTintColor = [UIColor purpleColor];
[self addSubview:pageControlVw];
_pageControlView = pageControlVw;
}
//value 對 Count 取模,並保證為正值
//這裡很重要,是實現無限循環的重要一步。比如現在顯示的是第一張圖片,_currentImgIndex=0,向左滑動後就顯示 _currentImgIndex+1 張圖片,但 _currentImgIndex+1 可能大於 _imgUrlArr 的 count,這裡取模;其次還要保證為正數,比如向右滑動時顯示 _currentImgIndex-1 張圖片,取模也可能為負數,此時加上 count 保證為正數
-(NSInteger)switchToMValue:(NSInteger)value Count:(NSInteger)count {
NSInteger result = value % count;
return result >= 0 ? result : result + count;
}
重寫 imgUrlArr 的 set 方法
-(void)setImgUrlArr:(NSArray *)imgUrlArr {
_imgUrlArr = [imgUrlArr copy];
NSInteger count = imgUrlArr.count;
if (count <= 0 ) {
return;
}
//如果只顯示一張圖片,那就沒有旋轉情況
if (count == 1) {
UIImageView *imgView = [[UIImageView alloc]init];
imgView.frame = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
[_contentScrollView addSubview:imgView];
_pageControlView.numberOfPages = 1;
_pageControlView.currentPage = 0;
_contentScrollView.contentSize = CGSizeMake(self.bounds.size.width, self.bounds.size.height);
NSURL *imgUrl = [NSURL URLWithString:imgUrlArr[0]];
[imgView sd_setImageWithURL:imgUrl placeholderImage:nil];
return;
}
if (count > 1) {
//這裡只用 3 個 ImgView 輪轉多張圖片,數量 2,3,4,5,6...
for(int i = 0; i < 3 ;i++) {
UIImageView *imgView = [[UIImageView alloc] init];
imgView.frame = CGRectMake(i * self.bounds.size.width, 0, self.bounds.size.width, self.bounds.size.height);
imgView.layer.masksToBounds = YES;
NSString *urlStr = _imgUrlArr[[self switchToValue:i-1 Count:count]];
NSURL *imgUrl = [NSURL URLWithString:urlStr];
[imgView sd_setImageWithURL:imgUrl placeholderImage:nil];
if (i == 0) {
_imgView1 = imgView;
} else if (i == 1) {
_imgView2 = imgView;
} else if (i == 2) {
_imgView3 = imgView;
}
[_contentScrollView addSubview:imgView];
}
_pageControlView.numberOfPages = count;
_pageControlView.currentPage = 0;
_contentScrollView.contentSize = CGSizeMake(self.bounds.size.width * 3, self.bounds.size.height);
_currentImgIndex = 0;
[_contentScrollView setContentOffset:CGPointMake(self.bounds.size.width, 0) animated:NO];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//循環輪轉圖片
[self switchImg];
});
}
}
5 秒旋轉圖片
-(void)switchImg {
while (1) {
[NSThread sleepForTimeInterval:WiatForSwitchImgMaxTime];
//如果正在拖拽圖片,此次作廢
if (_isDragImgView) {
continue;
}
_currentPage = [self switchToValue:_currentPage + 1 Count:_imgUrlArr.count];
dispatch_async(dispatch_get_main_queue(), ^{
_pageControlView.currentPage = _currentPage;
_contentScrollView.contentOffset = CGPointMake(2 * self.bounds.size.width, 0);
[self reSetImgUrlWithDirection:SwitchDirectionLeft];
});
}
}
當手動旋轉圖片
-(void)switchImgByDirection:(SwitchDirection)direction {
if (direction == SwitchDirectionNone) {
return;
}
[self reSetImgUrlWithDirection:direction];
[_contentScrollView setContentOffset:CGPointMake(self.bounds.size.width, 0) animated:NO];
}
旋轉圖片後重新調整 3 個 UIImageView 顯示的內容,如實現思想所述
-(void)reSetImgUrlWithDirection:(SwitchDirection)direction {
if (direction == SwitchDirectionRight) {
[_imgView1 sd_setImageWithURL:[NSURL URLWithString:_imgUrlArr[[self switchToValue:_currentImgIndex - 2 Count:_imgUrlArr.count]]] placeholderImage:nil];
[_imgView2 sd_setImageWithURL:[NSURL URLWithString:_imgUrlArr[[self switchToValue:_currentImgIndex - 1 Count:_imgUrlArr.count]]] placeholderImage:nil];
[_imgView3 sd_setImageWithURL:[NSURL URLWithString:_imgUrlArr[[self switchToValue:_currentImgIndex Count:_imgUrlArr.count]]] placeholderImage:nil];
_currentImgIndex = [self switchToValue:_currentImgIndex - 1 Count:_imgUrlArr.count];
} else if(direction == SwitchDirectionLeft) {
[_imgView1 sd_setImageWithURL:[NSURL URLWithString:_imgUrlArr[[self switchToValue:_currentImgIndex Count:_imgUrlArr.count]]] placeholderImage:nil];
[_imgView2 sd_setImageWithURL:[NSURL URLWithString:_imgUrlArr[[self switchToValue:_currentImgIndex + 1 Count:_imgUrlArr.count]]] placeholderImage:nil];
[_imgView3 sd_setImageWithURL:[NSURL URLWithString:_imgUrlArr[[self switchToValue:_currentImgIndex + 2 Count:_imgUrlArr.count]]] placeholderImage:nil];
_currentImgIndex = [self switchToValue:_currentImgIndex + 1 Count:_imgUrlArr.count];
}
}
實現 UIScrollView 三個代理方法
#pragma mark -------------Delegate---------------
//記住滑動的方向
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
static float newx = 0;
static float oldx = 0;
newx = scrollView.contentOffset.x ;
if (newx != oldx ) {
if (newx > oldx) {
_swDirection = SwitchDirectionLeft;
}else if(newx < oldx) {
_swDirection = SwitchDirectionRight;
}
oldx = newx;
}
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
_isDragImgView = YES;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
//向左旋轉
if (_swDirection == SwitchDirectionLeft) {
_currentPage = [self switchToValue:_currentPage + 1 Count:_imgUrlArr.count];
}//向右旋轉
else if (_swDirection == SwitchDirectionRight) {
_currentPage = [self switchToValue:_currentPage - 1 Count:_imgUrlArr.count];
}
_pageControlView.currentPage = _currentPage;
if (_swDirection != SwitchDirectionNone) {
[self switchImgByDirection:_swDirection];
}
_isDragImgView = NO;
}
以上為實現代碼,現在看看怎麼用,例如:
JGCirculateSwitchImgView *jView = [[JGCirculateSwitchImgView alloc] initWithFrame:CGRectMake(20,100, 280, 250)]; NSArray *imgUrlArr = @[@"https://www.blisscake.cn/Upload/Product/Show/Source/ps_1507201119031647109.jpg", @"https://www.blisscake.cn/Upload/Product/Show/Source/ps_1507201116215754685.jpg", @"https://www.blisscake.cn/Upload/Product/Show/Source/ps_1507201115524758041.jpg", @"https://www.blisscake.cn/Upload/Product/Show/Source/ps_1507201114495822068.jpg", @"https://www.blisscake.cn/Upload/Product/Show/Source/ps_1507201107522493367.jpg"]; jView.imgUrlArr = imgUrlArr; [self.view addSubview:jView];
可以看到封裝之後,代碼的複用性很高,使用起來很簡單,就這麼四句代碼就能實現圖片的無限循環輪轉。以上就是本文的全部內容,希望對大家的學習有所幫助。