iOS开发之图片左右无限轮播

最近相对来说不是很忙,所以网上看了一些别人写的框架的源码,印象深刻的是SDCycleScrollView这个第三方框架,写的也非常好,github上面的评星也5千多,查看了源码之后大概思路是用UICollectionView来做的,按照分页滚动,传入多少张图片就乘以100,然后代码来操作UICollectionView滚动到一半的位置,这样操作的话用户短时间内是滑不出这么多的;然后我手动滑动到最后一个测试过,还是有一闪而过的操作,个人感觉不太友好,(这里仅代表本人对这个框架的看法)所以今天我写了这个工具类,记录一下

思路:使用三个控件左右更换位置

SHInfiniteShufflingView.h

#import <UIKit/UIKit.h>

typedef void(^DidSlectIndex)(NSInteger index,NSString *url);
/*!
 *无限循环图片轮播
 */
@interface SHInfiniteShufflingView : UIScrollView

/// 设置图片和间隔时间
/// @param dataArray 图片数组(自动识别远程地址和本地图片)
/// @param time 间隔时间,0代表不启动定时器(自动创建和销毁定时器)
- (void)setImageArray:(NSArray *)dataArray InteralTime:(NSInteger)time;
/*!
 *页码
 */
@property (nonatomic , strong) UIPageControl *pageControl;
/*!
 *点击回调
 */
@property (nonatomic , copy) DidSlectIndex didSlect;

@end

SHInfiniteShufflingView.m

#import "SHInfiniteShufflingView.h"
#import <SDWebImage.h>

@interface SHInfiniteShufflingView ()<UIScrollViewDelegate>
@property (nonatomic , strong) NSMutableArray *subViewArray;
@property (nonatomic , assign) BOOL isCanRolling;
@property (nonatomic , copy) NSArray  *imageArray;
@property (nonatomic , assign) NSInteger intervalSecond;
@end

@implementation SHInfiniteShufflingView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _isCanRolling = YES;
        self.pagingEnabled = YES;
        self.bounces = NO;
        self.delegate = self;
        self.showsVerticalScrollIndicator = NO;
        self.showsHorizontalScrollIndicator = NO;
        [self addSubview:self.pageControl];
    }
    return self;
}
- (void)layoutSubviews
{
    [super layoutSubviews];
    self.pageControl.frame = CGRectMake(self.contentOffset.x, self.frame.size.height-30, self.frame.size.width, 30);
}
- (void)setImageArray:(NSArray *)dataArray InteralTime:(NSInteger)time
{
    if (dataArray.count == 0) return;
    _imageArray = dataArray;                    //初始化控件
    if (_imageArray.count == 1) {
        UIImageView *imageView = [[UIImageView alloc] init];
        NSString *imageUrl = _imageArray.lastObject;
        if ([imageUrl containsString:@"https://"] || [imageUrl containsString:@"http://"]) {
            [imageView sd_setImageWithURL:[NSURL URLWithString:imageUrl]];
        }else{
            imageView.image = [UIImage imageNamed:imageUrl];
        }
        imageView.userInteractionEnabled = YES;
        [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(panClick)]];
        imageView.frame = self.bounds;
        [self addSubview:imageView];
    }else{
        self.contentSize = CGSizeMake(self.frame.size.width*3,self.frame.size.height);
        [self setContentOffset:CGPointMake(self.frame.size.width, 0)];
        for (NSInteger i = 0; i < 3; i++) {
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.frame.size.width*i, 0, self.frame.size.width, self.frame.size.height)];
            NSString *imageUrl = _imageArray[i == 0 ? [self getLessNum] : i == 1 ? self.pageControl.currentPage : [self getMoreNum]];
            if ([imageUrl containsString:@"https://"] || [imageUrl containsString:@"http://"]) {
                [imageView sd_setImageWithURL:[NSURL URLWithString:imageUrl]];
            }else{
                imageView.image = [UIImage imageNamed:imageUrl];
            }
            imageView.userInteractionEnabled = YES;
            [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(panClick)]];
            [self addSubview:imageView];
            [self.subViewArray addObject:imageView];
        }
    }
    [self bringSubviewToFront:self.pageControl];
    self.pageControl.numberOfPages = _imageArray.count;
    if (self.imageArray.count > 1 && time > 0) {
        [NSTimer scheduledTimerWithTimeInterval:time repeats:YES block:^(NSTimer * _Nonnull timer) {
            if (self.isCanRolling) {
                [self setContentOffset:CGPointMake(self.frame.size.width*2, 0) animated:YES];
            }
        }];
    }
}
- (void)panClick
{
    !self.didSlect ? : self.didSlect(self.pageControl.currentPage,self.imageArray[self.pageControl.currentPage]);
}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self layoutIfNeeded];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (scrollView.contentOffset.x == 0 || scrollView.contentOffset.x == 2 * self.frame.size.width) {
        [self layoutSubview];
    }
}
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    if (scrollView.contentOffset.x == 0 || scrollView.contentOffset.x == 2 * self.frame.size.width) {
        [self layoutSubview];
    }
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    _isCanRolling = NO;
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    _isCanRolling = YES;
}
- (void)layoutSubview{
    if (self.contentOffset.x == 0 || self.imageArray.count == 0) {
        self.pageControl.currentPage = self.pageControl.currentPage == 0 ? self.imageArray.count-1 : self.pageControl.currentPage-1;
        [self.subViewArray exchangeObjectAtIndex:0 withObjectAtIndex:self.subViewArray.count-1];
        [self.subViewArray exchangeObjectAtIndex:1 withObjectAtIndex:self.subViewArray.count-1];
        UIImageView *imageView = self.subViewArray.firstObject;
        NSString *imageUrl = self.imageArray[[self getLessNum]];
        if ([imageUrl containsString:@"http://"] || [imageUrl containsString:@"https://"]) {
            [imageView sd_setImageWithURL:[NSURL URLWithString:imageUrl]];
        }else{
            imageView.image = [UIImage imageNamed:imageUrl];
        }
    }else{
        self.pageControl.currentPage = self.pageControl.currentPage == self.imageArray.count-1 ? 0 : self.pageControl.currentPage+1;
        [self.subViewArray exchangeObjectAtIndex:1 withObjectAtIndex:self.subViewArray.count-1];
        [self.subViewArray exchangeObjectAtIndex:0 withObjectAtIndex:self.subViewArray.count-1];
        UIImageView *imageView = self.subViewArray.lastObject;
        NSString *imageUrl = self.imageArray[[self getMoreNum]];
        if ([imageUrl containsString:@"http://"] || [imageUrl containsString:@"https://"]) {
            [imageView sd_setImageWithURL:[NSURL URLWithString:imageUrl]];
        }else{
            imageView.image = [UIImage imageNamed:imageUrl];
        }
    }
    NSInteger coun = self.subViewArray.count;
    for (NSInteger i = 0; i < coun; i++) {
        UIImageView *imageView = self.subViewArray[i];
        imageView.frame = CGRectMake(self.frame.size.width*i, 0, self.frame.size.width, self.frame.size.height);
    }
    [self setContentOffset:CGPointMake(self.frame.size.width, 0)];
}
#pragma mark - lazy
- (NSMutableArray *)subViewArray
{
    if (!_subViewArray) {
        _subViewArray = [NSMutableArray array];
    }
    return _subViewArray;
}
- (UIPageControl *)pageControl
{
    if (!_pageControl) {
        _pageControl = [[UIPageControl alloc] init];
        _pageControl.hidesForSinglePage = YES;
        _pageControl.currentPage = 0;
        _pageControl.numberOfPages = 1;
    }
    return _pageControl;
}
#pragma mark - customMetod
- (NSInteger)getMoreNum{
    return self.pageControl.currentPage == self.imageArray.count-1 ? 0 : self.pageControl.currentPage+1;
}
- (NSInteger)getLessNum
{
    return self.pageControl.currentPage == 0 ? self.imageArray.count-1 : self.pageControl.currentPage-1;
}
@end

代码量不多就没有单独写demo,小伙伴们可以直接复制过去就能运行,UI层面的封装,简单适配一下SDWebImage等相关框架,自动识别本地图片文件和远程图片文件,有点击事件block回调

使用

SHInfiniteShufflingView *shufflingView = [[SHInfiniteShufflingView alloc] initWithFrame:CGRectMake(0, 100, self.view.bounds.size.width, 300)];
    shufflingView.backgroundColor = UIColor.lightGrayColor;
    [shufflingView setImageArray:@[@"https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3984473917,238095211&fm=26&gp=0.jpg",
                                   @"https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2462146637,4274174245&fm=26&gp=0.jpg",
                                   @"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1596172460861&di=e7f4f1f6046e639b148a24af0d985443&imgtype=0&src=http%3A%2F%2Ffile02.16sucai.com%2Fd%2Ffile%2F2014%2F0929%2F0befba7c8a1702dec85affb2ef4cd90b.jpg",
                                   @"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1596172460856&di=ab20841811dc58d90a1121dff4373295&imgtype=0&src=http%3A%2F%2Fa2.att.hudong.com%2F48%2F69%2F01300000169041121120698749544.jpg",@"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1596189818908&di=7de8f60ed9c1930e0442f0d721b0453c&imgtype=0&src=http%3A%2F%2Fa0.att.hudong.com%2F56%2F12%2F01300000164151121576126282411.jpg"] InteralTime:3];
    shufflingView.didSlect = ^(NSInteger index, NSString *url) {
        NSLog(@"--%ld----%@",index,url);
    };
    [self.view addSubview:shufflingView];

完事,收工

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,427评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,551评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,747评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,939评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,955评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,737评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,448评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,352评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,834评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,992评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,133评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,815评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,477评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,022评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,147评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,398评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,077评论 2 355