iOS-封裝輪播圖Demo--兩個UIImageView實現(xiàn)無限輪播(1)

人生若只如初見,何事秋風(fēng)悲畫扇!<伊布家族>

先上圖:

無限輪播.gif

看到有些用 ScrollView 加三個 UIImageView 實現(xiàn)較為完美無限輪播,我就想著那用手勢加兩個 UIImageView應(yīng)該也是可以實現(xiàn)的,于是今天嘗試弄了一個初步小Demo! 【GitHub】

思路分析:
  • 用數(shù)組把需要展示的照片名稱存進(jìn)去, 有時間再去寫加載網(wǎng)絡(luò)照片吧!
  • 用一個屬性記錄當(dāng)前展示的圖片的下標(biāo),那么前一張和后一張的下標(biāo)自然可以表示出來。
  • 給封裝的View添加平移手勢, 讓當(dāng)前的ImageView跟隨者手勢一起移動。
  • 我們用兩個UIImageView展示圖片, 當(dāng)前ImageView展示著當(dāng)前下標(biāo)的照片,手勢向 左(右)滑動的時候,另個ImageView緊挨著當(dāng)前的ImageView,位于當(dāng)前ImageView的右(左)側(cè)!兩個ImageView一起滑動!
  • 手勢停止的時候,判斷需要展示哪個ImageView!并把記錄當(dāng)前照片的ImageView指針指向這個展示的照片,記錄下一個照片的指針指向不在視線的哪個ImageView。
  • 這樣就完成了一次滑動切換照片,其他重復(fù)這樣的操作就好了,在這基礎(chǔ)上添加定時器實現(xiàn)自動切換功能!

上代碼:
  • .h中聲明創(chuàng)建方法 :
/**
 創(chuàng)建方法
 @param imageArray 存放照片名稱的數(shù)組
 @param frame      位置
 */
- (instancetype)initWithImageArray:(NSArray <NSString *>*)imageArray
                              fram:(CGRect)frame;```

----
- .m中聲明的屬性

```code
@property (assign, nonatomic) NSInteger currentIndex;// 當(dāng)前展示視圖對應(yīng)的下標(biāo)
@property (assign, nonatomic) NSInteger nextIndex; // 對應(yīng)的下一個坐標(biāo)
@property (assign, nonatomic) NSInteger previousIndex;// 對應(yīng)上一個坐標(biāo)
@property (strong, nonatomic) UIPanGestureRecognizer *pan;// 手勢
@property (strong, nonatomic) NSArray<NSString *> *imageNames;// 存照片的名字?jǐn)?shù)組
@property (strong, nonatomic) UIImageView *currentImage;// 當(dāng)前展示的照片
@property (strong, nonatomic) UIImageView *nextImage; // 將要展示的照片

@property (strong, nonatomic) NSTimer *changeImageTime; // 定時器
// 定義一個滑動方向枚舉 手勢停止的時候判斷需要展示哪一張照片
typedef enum : NSUInteger
{
    MoveDirectionLeft,
    MoveDirectionRight,
} MoveDirection;```

---
 - 抽離獲取下標(biāo)和照片的方法
```code
 // 獲取當(dāng)前下標(biāo)下一個坐標(biāo)
- (NSInteger)nextIndex
{
    return _currentIndex == _imageNames.count - 1 ? 0 : _currentIndex + 1;
}
// 獲取當(dāng)前下標(biāo)的上一個坐標(biāo)
- (NSInteger)previousIndex
{
    return _currentIndex == 0 ? _imageNames.count - 1 : _currentIndex - 1;
}
// 根據(jù)下標(biāo)取到照片
- (UIImage *)getImageForIndex:(NSInteger)index
{
    return [UIImage imageNamed:[NSString stringWithFormat:@"LoopImg.bundle/%@",_imageNames[index]]];
}
  • 初始化方法
/ 初始化方法
- (instancetype)initWithImageArray:(NSArray <NSString *>*)imageArray
                              fram:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
//  存
        _imageNames = imageArray;
        _currentIndex = 0;
        _currentImage = [[UIImageView alloc] initWithFrame:self.bounds];
        _currentImage.userInteractionEnabled = YES;
        _currentImage.image = [self getImageForIndex:_currentIndex];
        [self insertSubview:_currentImage atIndex:1];  
        // 下一張圖片
        _nextImage = [[UIImageView alloc] init];
        _nextImage.userInteractionEnabled = YES;
        [self insertSubview:_nextImage atIndex:0];
        // 添加平移手勢
        // pan手勢處理切換
        _pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panChangeImage:)];
        [self addGestureRecognizer:_pan];
        
        // 添加定時器
        [self addTime];
           }
    return self;
}
  • 手勢事件
// 切換圖片
- (void)panChangeImage:(UIPanGestureRecognizer *)pan
{
    // 手勢的時候先移除 time
    [self.changeImageTime invalidate];
    self.changeImageTime = nil;
    
    // 向左滑 x 為負(fù) 向右滑 x 為正  (末位置 減 初始位置)
    CGPoint panOffSet = [pan translationInView:self];
    float changeX = panOffSet.x;
    NSLog(@"-------->%f",changeX);
    // 獲取 當(dāng)前的視圖位置
    CGRect frame = _currentImage.frame;
    // 清空手勢的偏移量
    [_pan setTranslation:(CGPointZero) inView:self];

    // 處理左右照片
    float resulet = frame.origin.x + (changeX < 0 ? - DBL_EPSILON : DBL_EPSILON);
   //  小于 0 就是向左滑動了 大于 0 就是向右 滑動 了
    resulet <= 0 ? [self leftScroll:changeX frame:frame] : [self rightScroll:changeX frame:frame] ;
}
  • 當(dāng)前照片左滑動 出現(xiàn)右側(cè)照片
- (void)leftScroll:(float)offX frame:(CGRect)frame
{// 記錄當(dāng)前的 滑動后的 x
    float tempX = frame.origin.x + offX;
    // 移動當(dāng)前的圖片
    _currentImage.frame = CGRectMake(tempX, frame.origin.y, frame.size.width, frame.size.height);
    // 設(shè)置下一張照片
    _nextImage.image = [self getImageForIndex:self.nextIndex];
    _nextImage.frame = CGRectOffset(_currentImage.frame, kScreenW, 0);
    
    // 手勢停止的時候
    if (_pan.state == UIGestureRecognizerStateEnded)
    {
        // 回復(fù)定時器
        [self addTime];
        // 判斷手勢停止的時候展示哪一個 照片
        MoveDirection result = tempX <= - kScreenW / 2 ? [self leftOut:_currentImage rightIn:_nextImage duration:0.3f] : [self leftIn:_currentImage rightOut:_nextImage duration:0.3f];
      
        // 判斷需要當(dāng)先展示的是下張圖片的時候  去操作
        if (result == MoveDirectionLeft)
        {
            _currentIndex = self.nextIndex;// 改變當(dāng)前展示的下標(biāo)
            // 交換 _nextImage 和 _currentImage 指針指向,這樣的話當(dāng)前的指針指向就是展示在當(dāng)前的界面的圖片
            UIImageView *temp = _nextImage;
            _nextImage = _currentImage;
            _currentImage = temp;
        }
    }  
}
  • 當(dāng)前圖片右滑動 出現(xiàn)左側(cè)照片
 - (void)rightScroll:(float)offX frame:(CGRect)frame
{
    float tempX = frame.origin.x + offX;
    // 移動當(dāng)前的圖片
    _currentImage.frame = CGRectMake(tempX, frame.origin.y, frame.size.width, frame.size.height);
    // 設(shè)置上一張照片
    _nextImage.image = [self getImageForIndex:self.previousIndex];
    _nextImage.frame = CGRectOffset(_currentImage.frame, -kScreenW, 0);
    
    // 收拾停止的時候
    if (_pan.state == UIGestureRecognizerStateEnded)
    {
        // 回復(fù)定時器
        [self addTime];
        
        // 判斷手勢停止的時候展示哪一個 照片
        MoveDirection result = tempX <= kScreenW / 2 ? [self leftOut:_nextImage rightIn:_currentImage duration:0.3f] : [self leftIn:_nextImage rightOut:_currentImage duration:0.3f];
        
        // 要展示上一張照片
        if (result == MoveDirectionRight)
        {
            _currentIndex = self.previousIndex;
            UIImageView *temp = _nextImage;
            _nextImage = _currentImage;
            _currentImage = temp;
        }
    }
}```


 - 抽離代碼,手勢結(jié)束時候 判斷兩個UIImageView展示哪一個,并用動畫調(diào)整好位置。
```code
// 最終展示右側(cè)的圖片
- (MoveDirection)leftOut:(UIImageView *)leftView rightIn:(UIImageView *)rightView duration:(NSTimeInterval)duration
{/*
     當(dāng)手勢結(jié)束的時候  左邊的 ImageView 滑出視線之外  右側(cè)的 ImageView 占據(jù)整個屏幕
     */
    [UIView animateWithDuration:duration animations:^{
        leftView.frame = CGRectOffset(self.bounds, - kScreenW, 0);
        rightView.frame = self.bounds;
    } completion:^(BOOL finished) 
{    
    }];
    return MoveDirectionLeft;
}
// 最終展示
- (MoveDirection)leftIn:(UIImageView *)leftView rightOut:(UIImageView *)rightView duration:(NSTimeInterval)duration
{
    /*
     當(dāng)手勢結(jié)束的時候  展示位于左邊的照片 右側(cè)的看不見
     */
    [UIView animateWithDuration:duration animations:^{
        rightView.frame = CGRectOffset(self.bounds, kScreenW, 0);
        leftView.frame = self.bounds;
    } completion:^(BOOL finished) {
        
    }];
    return MoveDirectionRight;
}``` 

 - 設(shè)置定時器
```code
- (void)addTime
{
    _changeImageTime = [NSTimer scheduledTimerWithTimeInterval:1.5f target:self selector:@selector(changeActionForTime) userInfo:nil repeats:YES];
}
- (void)changeActionForTime
{
    // 設(shè)置下一張照片
    self.nextImage.image = [self getImageForIndex:self.nextIndex];
    self.nextImage.frame = CGRectOffset(_currentImage.frame, kScreenW, 0);
    [self leftOut:self.currentImage rightIn:self.nextImage duration:0.5f];
    self.currentIndex = self.nextIndex;// 改變當(dāng)前展示的下標(biāo)
    // 交換 _nextImage 和 _currentImage 指針指向,這樣的話當(dāng)前的指針指向就是展示在當(dāng)前的界面的圖片
    UIImageView *temp = self.nextImage;
    self.nextImage = self.currentImage;
    self.currentImage = temp;
}

PS:整體的代碼沒有調(diào)整的太好,大家見諒哈!有時間我在好好整理一下!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容