圖片輪播器(使用一個UIImageView實現(xiàn)輪播器的功能)

在iOS開發(fā)中,實現(xiàn)一個圖片輪播器的方法有好多種,比如使用UIScrollView、UICollectionView或者利用三個UIImageView,以前三種方法都能實現(xiàn)一個圖片輪播器的功能,這里使用的是利用一個UIImageView來實現(xiàn)。

首先,新建一個InfinitudeView,在.m文件中看下需要設(shè)置的屬性

@interface InfinitudeView ()

@property (nonatomic, weak) UIImageView *imgView; /**< 圖片容器 */
@property (nonatomic, assign) NSInteger index; /**< 圖片索引 */
@property (nonatomic, assign) NSInteger imageCount; /**< 圖片數(shù)量 */
@property (nonatomic, strong) NSTimer *timer; /**< 定時器 */
@property (nonatomic, weak) UILabel *showCountLabel; /**< 顯示索引 */

@property (nonatomic, strong) UISwipeGestureRecognizer *leftSwipeGesture; /**< 左滑手勢 */
@property (nonatomic, strong) UISwipeGestureRecognizer *rightSwipeGesture; /**< 右滑手勢 */

@end

1.顯示圖片和圖片的索引

    UIImageView *imgView = [[UIImageView alloc] initWithFrame:self.bounds];
    imgView.contentMode = UIViewContentModeScaleAspectFit;
    [self addSubview:imgView];
    self.imgView = imgView;

    UILabel *showCountLabel = [[UILabel alloc] init];
    [self addSubview:showCountLabel];
    self.showCountLabel = showCountLabel;
    showCountLabel.translatesAutoresizingMaskIntoConstraints = NO;
    showCountLabel.font = [UIFont systemFontOfSize:15.0f];
    [self addConstraints:@[
                           [NSLayoutConstraint constraintWithItem:showCountLabel attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeRight multiplier:1.0f constant:-20],
                           [NSLayoutConstraint constraintWithItem:showCountLabel attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeBottom multiplier:1.0f constant:-20]]
                          ];

2.在.h文件中添加一個圖片數(shù)組,用于數(shù)據(jù)傳遞進來

@interface InfinitudeView : UIView

@property (nonatomic, strong) NSArray *imageArray; /**< 圖片數(shù)組 */

@end

3.重寫imageArray的setter方法,當(dāng)傳入圖片的時候,設(shè)置好

/**
 *  根據(jù)圖片數(shù)組設(shè)置圖片
 *
 *  @param imageArray 圖片數(shù)組
 */
- (void)setImageArray:(NSArray *)imageArray {
    
    _imageArray = imageArray;
    _imageCount = imageArray.count;
    _index = 0;
    [self setImage];
}

4.數(shù)組可以傳入圖片或者圖片的鏈接字符串,因此需要做一下判斷,加載網(wǎng)絡(luò)圖片為了簡單一些,直接使用的第三方SDWebImage

/**
 *  設(shè)置圖片
 */
- (void)setImage {
    
    // 顯示圖片索引
    [self setShowCountLabelText];
    id object = [_imageArray firstObject];
    // 如果傳入的是圖片則直接顯示圖片,如果是圖片鏈接,網(wǎng)絡(luò)加載
    if ([object isKindOfClass:[UIImage class]]) {
        _imgView.image = _imageArray[_index];
    } else if ([object isKindOfClass:[NSMutableString class]]) {
        [_imgView sd_setImageWithURL:[NSURL URLWithString:_imageArray[_index]]];
    }
}

5.索引的設(shè)置

/**
 *  顯示索引
 */
- (void)setShowCountLabelText {
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
    NSAttributedString *str1 = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%zd", _index + 1] attributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:0.915 green:0.685 blue:0.574 alpha:1.000]}];
    NSAttributedString *str2 = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"/%zd", _imageCount] attributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    [attributedString appendAttributedString:str1];
    [attributedString appendAttributedString:str2];
    _showCountLabel.attributedText = attributedString;
}

到目前為止,運行效果

1.png

6.添加手勢

/**
 *  添加手勢
 */
- (void)addGuesture {
    
    // 1.添加左滑動手勢
    _leftSwipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(gestureMethod:)];
    _leftSwipeGesture.direction = UISwipeGestureRecognizerDirectionLeft;
    [self addGestureRecognizer:_leftSwipeGesture];
    
    // 2.添加右滑動手勢
    _rightSwipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(gestureMethod:)];
    _rightSwipeGesture.direction = UISwipeGestureRecognizerDirectionRight;
    [self addGestureRecognizer:_rightSwipeGesture];
}

7.手持的響應(yīng)方法

/**
 *  手勢響應(yīng)方法
 *
 *  @param swipeGesture 響應(yīng)的手勢
 */
- (void)gestureMethod:(UISwipeGestureRecognizer *)swipeGesture {
    
    switch (swipeGesture.direction) {
        case UISwipeGestureRecognizerDirectionLeft:
            _index++;
            [self setImageWithIndex:_index];
            [self animationTransitionWithSwipeGestureRecognizerDirection:swipeGesture.direction];
            break;
        case UISwipeGestureRecognizerDirectionRight:
            _index--;
            [self setImageWithIndex:_index];
            [self animationTransitionWithSwipeGestureRecognizerDirection:swipeGesture.direction];
            break;
        default:break;
    }
}

8.根據(jù)滑動設(shè)置圖片

/**
 *  根據(jù)手勢設(shè)置圖片
 */
- (void)setImageWithIndex:(NSInteger)index {
    
    if (index > _imageCount - 1) {
        _index = 0;
    } else if (index < 0) {
        _index = _imageCount - 1;
    }
    
    [self setImage];
}

9.設(shè)置轉(zhuǎn)場動畫

/**
 *  添加轉(zhuǎn)場動畫
 *
 *  @param direction 手勢方向
 */
- (void)animationTransitionWithSwipeGestureRecognizerDirection:(UISwipeGestureRecognizerDirection)direction {
    
    CATransition *transition = [CATransition animation];
    transition.duration = 0.5f;
    // 設(shè)置動畫的樣式
    transition.type = kCATransitionPush;
    if (direction == UISwipeGestureRecognizerDirectionRight) {
        transition.subtype = @"fromLeft";
    } else {
        transition.subtype = @"fromRight";
    }
    [_imgView.layer addAnimation:transition forKey:nil];
}

運行

2.gif

9.接下來是添加一個定時器,在傳入圖片的時候添加

/**
 *  根據(jù)圖片數(shù)組設(shè)置圖片
 *
 *  @param imageArray 圖片數(shù)組
 */
- (void)setImageArray:(NSArray *)imageArray {
    
    _imageArray = imageArray;
    _imageCount = imageArray.count;
    _index = 0;
    _timer = [NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(timerMethod) userInfo:nil repeats:YES];
    [self setImage];
}

/**
 *  定時器響應(yīng)方法
 */
- (void)timerMethod {

    _index++;
    [self setImageWithIndex:_index];
    [self animationTransitionWithSwipeGestureRecognizerDirection:_leftSwipeGesture.direction];
}

當(dāng)滑動的時候,定時器需要關(guān)閉

/**
 *  手勢響應(yīng)方法
 *
 *  @param swipeGesture 響應(yīng)的手勢
 */
- (void)gestureMethod:(UISwipeGestureRecognizer *)swipeGesture {
    
    [_timer invalidate];
    switch (swipeGesture.direction) {
        case UISwipeGestureRecognizerDirectionLeft:
            _index++;
            [self setImageWithIndex:_index];
            [self animationTransitionWithSwipeGestureRecognizerDirection:swipeGesture.direction];
            break;
        case UISwipeGestureRecognizerDirectionRight:
            _index--;
            [self setImageWithIndex:_index];
            [self animationTransitionWithSwipeGestureRecognizerDirection:swipeGesture.direction];
            break;
        default:break;
    }
    _timer = [NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(timerMethod) userInfo:nil repeats:YES];
}

再看看整體效果

3.gif

整體代碼
https://github.com/JudeGGT/-

最后編輯于
?著作權(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)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,244評論 4 61
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,001評論 25 709
  • 文章首發(fā)于原創(chuàng)公眾號:畢業(yè)不等于失業(yè) id:bybdysy 一 經(jīng)常有朋友私信我: 我應(yīng)該去做兼職嗎? 我應(yīng)該去考...
    86e280374491閱讀 368評論 1 0
  • 覺察日記20170406+何娜+3w4 自導(dǎo)自演 “伊能靜47歲拼命生下一個女兒,大家都以為是嫁給愛情的,看到文章...
    Bemy閱讀 355評論 2 3

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