iOS学习笔记之轮播图

思路

采用了最常见的方法,将所要展示的轮播图放在UIScrollView上,并将第一张加到最后,最后一张加到开头,以三张图为例,如下图:

iOS学习笔记之轮播图_第1张图片
轮播图原理图

轮播图滑动到1s时,将偏移量移动到1的位置,滑动到3s时,将偏移量移动到3的位置,这个过程是没有动画的,所以用户看不出来,这就实现轮播图的循环滚动。

代码

1.自定义一个继承UIView的HomeBannerView,当然,名字根据自己的喜好来定。

定义了两个常用的宏

#define VIEW_WIDTH self.bounds.size.width
#define VIEW_HEIGHT self.bounds.size.height

给HomeBannerView定义一些属性,其中block回调实现轮播图的点击跳转事件,banners中存放的模型,currentSelectedPage是当前的页数。

@property (copy, nonatomic) void(^block)(NSInteger);
@property (strong, nonatomic) NSMutableArray *banners;
@property (strong, nonatomic) UIScrollView *scrollView;
@property (strong, nonatomic) UIPageControl *pageControl;
@property (assign, nonatomic) NSUInteger currentSelectedPage;
@property (strong, nonatomic) NSTimer *timer;

- (void)loadData;

重写HomeBannerView的initWithFrame:函数,调用设置UI的函数。

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame: frame]) {
        [self setupUI];
    }
    return self;
}

设置UI:设置scrollView和pageControl的基本属性,并给scrollView添加单击手势。

- (void)setupUI {
    
    // 设置scrollView
    self.scrollView = [[UIScrollView alloc] initWithFrame:self.frame];
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.pagingEnabled = YES;
    self.scrollView.bounces = NO;
    self.scrollView.delegate = self;
    [self addSubview:self.scrollView];
    
    // 设置pageControl
    self.pageControl = [[UIPageControl alloc] init];
    self.pageControl.userInteractionEnabled = NO;
    [self addSubview:self.pageControl];
    [self.pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.mas_centerX);
        make.bottom.mas_equalTo(self);
    }];
    
    // 添加单击手势
    UITapGestureRecognizer *tapGestureRecognize = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureRecognizer:)];
    tapGestureRecognize.delegate = self;
    tapGestureRecognize.numberOfTapsRequired = 1;
    [_scrollView addGestureRecognizer:tapGestureRecognize];
}

设置定时器,定时器事件中让当前页数+1,然后更改scrollView的偏移量,这时就会调用scrollViewDidScroll:函数。

- (void)setupTimer {
    self.timer = [NSTimer timerWithTimeInterval:3.0 target:self selector:@selector(timerEvent) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)timerEvent {
    _currentSelectedPage ++;
    [_scrollView setContentOffset:CGPointMake(VIEW_WIDTH * (_currentSelectedPage + 1), 0) animated:YES];
}

加载请求到的数据,这里也可以写成带参函数,将模型数组传进来。

- (void)loadData {
    
    // 移除之前视图
    for (UIView *subView in _scrollView.subviews) {
        if ([subView isKindOfClass:[UIImageView class]]) {
            [subView removeFromSuperview];
        }
    }
    
    if (self.banners.count == 0) {
        // 显示默认页,无数据页面
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, VIEW_HEIGHT)];
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.image = [UIImage imageNamed:@""]; // 设置默认图片
        [_scrollView addSubview:imageView];
        return;
    }
    
    _pageControl.numberOfPages = self.banners.count;
    _pageControl.currentPage = 0;
    
    // 这里就是前文提到的,首尾各添加一张图片
    [self.banners insertObject:self.banners.lastObject atIndex:0];
    [self.banners addObject:[self.banners objectAtIndex:1]];
    
    _scrollView.contentSize = CGSizeMake(VIEW_WIDTH * self.banners.count, VIEW_HEIGHT);
    
    for (NSInteger i = 0; i < self.banners.count; i ++) {
        
        CGRect imgRect = CGRectMake(VIEW_WIDTH * i, 0, VIEW_WIDTH, VIEW_HEIGHT);
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:imgRect];
        BannerModel *banner = self.banners[i];
        [imageView sd_setImageWithURL:[NSURL URLWithString:banner.image_path]];
        [_scrollView addSubview:imageView];
    }
    
    if (self.banners.count > 1) {
        _scrollView.contentOffset = CGPointMake(VIEW_WIDTH, 0);
    } else {
        _scrollView.contentOffset = CGPointZero;
    }
    
    // 最开始setupTimer添加到initWithFrame:函数中,这样当banners.count == 0的时候,也会调用定时器,就会偏移到一片空白,放在这里比较合理。
    [self setupTimer];
}

scrollView滚动时调用这个方法,在这里判断偏移量,在这里实现前文思路中提到的1s变1,3s变3的过程。

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat targetX = scrollView.contentOffset.x;
    
    if (self.banners.count >= 3) {
        if (targetX >= VIEW_WIDTH * (self.banners.count - 1)) {
            targetX = VIEW_WIDTH;
        } else if (targetX <= 0) {
            targetX = VIEW_WIDTH * (self.banners.count - 2);
        }
        _scrollView.contentOffset = CGPointMake(targetX, 0);
    }
    
    NSInteger page = (scrollView.contentOffset.x + VIEW_WIDTH * 0.5) / VIEW_WIDTH;
    
    if (self.banners.count > 1) {
        page--;
        if (page >= _pageControl.numberOfPages) {
            page = 0;
        } else if (page < 0) {
            page = _pageControl.numberOfPages - 1;
        }
    }
    
    _currentSelectedPage = page;
    _pageControl.currentPage = page;
}

开始拖动的时候关闭定时器,结束拖动的时候开启定时器。

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    // 关闭定时器
    [self.timer invalidate];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    // 开启定时器
    [self setupTimer];
}

scrollView的点击事件,通过block来实现页面的跳转,根据偏移量判断当前点击的是第几个轮播图。

- (void)singleTapGestureRecognizer:(UITapGestureRecognizer *)tapGesture {
    NSInteger page = (NSInteger)(_scrollView.contentOffset.x / VIEW_WIDTH);
    self.block(page);
}
2.接下来的方法是在控制器中实现的

将bannerView添加到控制器中。

self.bannerView = [[HomeBannerView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, bannerHeight)];
[self.view addSubview:_bannerView];

__weak HomeViewController *weakSelf = self;
self.bannerView.block = ^(NSInteger page){
    // 跳转界面的代码写这里
};

在请求到数据之后给bannerView的banners赋值,然后调用bannerView的loadData函数。

self.bannerView.banners = 请求到的数据;
[self.bannerView loadData];

这样轮播图的功能就实现了。

你可能感兴趣的:(iOS学习笔记之轮播图)