美文网首页UIKitiOS技术iOS 开发
iOS-封装轮播图Demo--两个UIImageView实现无限

iOS-封装轮播图Demo--两个UIImageView实现无限

作者: 云之君兮鹏 | 来源:发表于2016-09-25 18:09 被阅读1749次

人生若只如初见,何事秋风悲画扇!<伊布家族>

先上图:

无限轮播.gif

看到有些用 ScrollView 加三个 UIImageView 实现较为完美无限轮播,我就想着那用手势加两个 UIImageView应该也是可以实现的,于是今天尝试弄了一个初步小Demo! 【GitHub】

思路分析:
  • 用数组把需要展示的照片名称存进去, 有时间再去写加载网络照片吧!
  • 用一个属性记录当前展示的图片的下标,那么前一张和后一张的下标自然可以表示出来。
  • 给封装的View添加平移手势, 让当前的ImageView跟随者手势一起移动。
  • 我们用两个UIImageView展示图片, 当前ImageView展示着当前下标的照片,手势向 左(右)滑动的时候,另个ImageView紧挨着当前的ImageView,位于当前ImageView的右(左)侧!两个ImageView一起滑动!
  • 手势停止的时候,判断需要展示哪个ImageView!并把记录当前照片的ImageView指针指向这个展示的照片,记录下一个照片的指针指向不在视线的哪个ImageView。
  • 这样就完成了一次滑动切换照片,其他重复这样的操作就好了,在这基础上添加定时器实现自动切换功能!

上代码:
  • .h中声明创建方法 :
/**
 创建方法
 @param imageArray 存放照片名称的数组
 @param frame      位置
 */
- (instancetype)initWithImageArray:(NSArray <NSString *>*)imageArray
                              fram:(CGRect)frame;```

----
- .m中声明的属性

```code
@property (assign, nonatomic) NSInteger currentIndex;// 当前展示视图对应的下标
@property (assign, nonatomic) NSInteger nextIndex; // 对应的下一个坐标
@property (assign, nonatomic) NSInteger previousIndex;// 对应上一个坐标
@property (strong, nonatomic) UIPanGestureRecognizer *pan;// 手势
@property (strong, nonatomic) NSArray<NSString *> *imageNames;// 存照片的名字数组
@property (strong, nonatomic) UIImageView *currentImage;// 当前展示的照片
@property (strong, nonatomic) UIImageView *nextImage; // 将要展示的照片

@property (strong, nonatomic) NSTimer *changeImageTime; // 定时器
// 定义一个滑动方向枚举 手势停止的时候判断需要展示哪一张照片
typedef enum : NSUInteger
{
    MoveDirectionLeft,
    MoveDirectionRight,
} MoveDirection;```

---
 - 抽离获取下标和照片的方法
```code
 // 获取当前下标下一个坐标
- (NSInteger)nextIndex
{
    return _currentIndex == _imageNames.count - 1 ? 0 : _currentIndex + 1;
}
// 获取当前下标的上一个坐标
- (NSInteger)previousIndex
{
    return _currentIndex == 0 ? _imageNames.count - 1 : _currentIndex - 1;
}
// 根据下标取到照片
- (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 为负 向右滑 x 为正  (末位置 减 初始位置)
    CGPoint panOffSet = [pan translationInView:self];
    float changeX = panOffSet.x;
    NSLog(@"-------->%f",changeX);
    // 获取 当前的视图位置
    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] ;
}
  • 当前照片左滑动 出现右侧照片
- (void)leftScroll:(float)offX frame:(CGRect)frame
{// 记录当前的 滑动后的 x
    float tempX = frame.origin.x + offX;
    // 移动当前的图片
    _currentImage.frame = CGRectMake(tempX, frame.origin.y, frame.size.width, frame.size.height);
    // 设置下一张照片
    _nextImage.image = [self getImageForIndex:self.nextIndex];
    _nextImage.frame = CGRectOffset(_currentImage.frame, kScreenW, 0);
    
    // 手势停止的时候
    if (_pan.state == UIGestureRecognizerStateEnded)
    {
        // 回复定时器
        [self addTime];
        // 判断手势停止的时候展示哪一个 照片
        MoveDirection result = tempX <= - kScreenW / 2 ? [self leftOut:_currentImage rightIn:_nextImage duration:0.3f] : [self leftIn:_currentImage rightOut:_nextImage duration:0.3f];
      
        // 判断需要当先展示的是下张图片的时候  去操作
        if (result == MoveDirectionLeft)
        {
            _currentIndex = self.nextIndex;// 改变当前展示的下标
            // 交换 _nextImage 和 _currentImage 指针指向,这样的话当前的指针指向就是展示在当前的界面的图片
            UIImageView *temp = _nextImage;
            _nextImage = _currentImage;
            _currentImage = temp;
        }
    }  
}
  • 当前图片右滑动 出现左侧照片
 - (void)rightScroll:(float)offX frame:(CGRect)frame
{
    float tempX = frame.origin.x + offX;
    // 移动当前的图片
    _currentImage.frame = CGRectMake(tempX, frame.origin.y, frame.size.width, frame.size.height);
    // 设置上一张照片
    _nextImage.image = [self getImageForIndex:self.previousIndex];
    _nextImage.frame = CGRectOffset(_currentImage.frame, -kScreenW, 0);
    
    // 收拾停止的时候
    if (_pan.state == UIGestureRecognizerStateEnded)
    {
        // 回复定时器
        [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;
        }
    }
}```


 - 抽离代码,手势结束时候 判断两个UIImageView展示哪一个,并用动画调整好位置。
```code
// 最终展示右侧的图片
- (MoveDirection)leftOut:(UIImageView *)leftView rightIn:(UIImageView *)rightView duration:(NSTimeInterval)duration
{/*
     当手势结束的时候  左边的 ImageView 滑出视线之外  右侧的 ImageView 占据整个屏幕
     */
    [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
{
    /*
     当手势结束的时候  展示位于左边的照片 右侧的看不见
     */
    [UIView animateWithDuration:duration animations:^{
        rightView.frame = CGRectOffset(self.bounds, kScreenW, 0);
        leftView.frame = self.bounds;
    } completion:^(BOOL finished) {
        
    }];
    return MoveDirectionRight;
}``` 

 - 设置定时器
```code
- (void)addTime
{
    _changeImageTime = [NSTimer scheduledTimerWithTimeInterval:1.5f target:self selector:@selector(changeActionForTime) userInfo:nil repeats:YES];
}
- (void)changeActionForTime
{
    // 设置下一张照片
    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;// 改变当前展示的下标
    // 交换 _nextImage 和 _currentImage 指针指向,这样的话当前的指针指向就是展示在当前的界面的图片
    UIImageView *temp = self.nextImage;
    self.nextImage = self.currentImage;
    self.currentImage = temp;
}

PS:整体的代码没有调整的太好,大家见谅哈!有时间我在好好整理一下!

相关文章

网友评论

  • e87663c46328:以前也尝试用两个imageView写过,好像有些问题,有时间研究一下你的代码 :smile:
  • CYC666:我的问题是:手势左右滑动没有离开屏幕,这样子的话,左右会显示什么呢?
    云之君兮鹏:@CYC666 恩,没有离开的话没事的!你手不离开屏幕,顶多能看到两个照片,往右滑看到左边,往左滑看到右边的!不离开屏幕也一样!手势是一直监听的!
  • Samson_Xu:给楼主点个赞,参考别人写过三个的,也写过五个的。之前一直觉得两个是不是也可以,但是太懒,没有动手去写 :smile: 为楼主的行动力点个赞! :+1:
    云之君兮鹏:@Samson_Xu 谢谢你 今天把网络照片加了
  • 小明大神:不错不错,学习了
    云之君兮鹏: @小明大神 谢谢
  • 爱阿爸的阿龙龙:挺好的 点赞
    云之君兮鹏:@爱阿爸的阿龙龙868 谢谢

本文标题:iOS-封装轮播图Demo--两个UIImageView实现无限

本文链接:https://www.haomeiwen.com/subject/brefyttx.html