网络知识 娱乐 iOS轮播图的简单实现

iOS轮播图的简单实现

平常在开发过程中,首页的轮播图总是少不了,轮播图我们都知道肯定是要使用 UIScrollView ,难点就在最后一张图片被滑动时,如何回到第一张图片以及第一张滑动到最后一张。
我们可以使用如下方式实现轮播图,在划到3后面的1后,设置 contentOffset 回到最先的1,并设置 pageControl ,即可达到效果 (从1划到3也同理)

看一下效果:


完成这种轮播图,我们的 View 需要如下的属性和方法

@interface RoundView : UIView

@property (nonatomic,strong) UIScrollView   *scrollView;
//存放ScrollView每一个page的图片的array
@property (nonatomic) NSMutableArray        *imgArray;
@property (nonatomic) UIPageControl         *pageControl;
//定时器
@property (nonatomic,strong) NSTimer        *__nullable timer;

- (instancetype)initWithFrame:(CGRect)frame imgArray:(NSArray *)array;

@end

在创建View的时候使用 initWithFrame:(CGRect)frame imgArray:(NSArray *)array,传入需要展示的 imgArray ,在 view 内进行处理。

在该方法的实现中,首先就是对图片数组array的处理,得到我们需要的imgArray

- (instancetype)initWithFrame:(CGRect)frame imgArray:(NSArray *)array{
    self=[super initWithFrame:frame];
    
    self.imgArray=[[NSMutableArray alloc]init];
    [self.imgArray addObject:[array lastObject]];
    [self.imgArray addObjectsFromArray:array];
    [self.imgArray addObject:[array firstObject]];
}

这样,我们的 imgArray 就变成了最开始演示原理的样式,为 @[first object,array,lastobject]

 然后我们初始化一下 ScrollView

    self.scrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
    [self.scrollView.layer setCornerRadius:10.0];
    self.scrollView.contentSize=CGSizeMake(frame.size.width * self.imgArray.count, frame.size.height);
    self.scrollView.pagingEnabled=YES;
    self.scrollView.contentOffset=CGPointMake(frame.size.width, 0);
    self.scrollView.showsVerticalScrollIndicator=NO;
    self.scrollView.showsHorizontalScrollIndicator=NO;
    self.scrollView.delegate=self;
    [self.scrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];

很简单,就是一些属性、代理的设置 根据 imgArray 的大小设置 contentSize ,另外对 contentOffset 添加一个观察者,方便后续对pageControl和contentOffset进行设置。

然后,我们根据 imgArray 将图片填入到 scrollView 中

    for(int i=0;i<self.imgArray.count;i++){
        CGRect imgFrame=CGRectMake(frame.size.width* i, 0, frame.size.width , frame.size.height);
        UIImageView* imgView=[[UIImageView alloc]initWithFrame:imgFrame];
        //这里我就不传入图片了,测试的imgArray中为颜色,使用颜色替代
        imgView.backgroundColor=self.imgArray[i];
        [self.scrollView addSubview:imgView];
    }

然后对pageControl和timer进行初始化

    self.pageControl=[[UIPageControl alloc]initWithFrame:CGRectMake(0, frame.size.height-20, frame.size.width, 20)];
    self.pageControl.numberOfPages=array.count;
    self.pageControl.currentPage=0;
    self.pageControl.tintColor=[UIColor whiteColor];
    
    self.timer=[NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(scrollImage) userInfo:nil repeats:YES];
    //添加到runloop中
    NSRunLoop *runloop=[NSRunLoop currentRunLoop];
    [runloop addTimer:self.timer forMode:NSRunLoopCommonModes];
    
    [self addSubview:self.scrollView];
    [self addSubview:self.pageControl];

这里设置的是5秒钟后自动滚动轮播图,可以根据需要自己设置,scrollmage 方法后面会讲


我们看一下我们需要的 scrollView 的代理方法

1.scrollViewDidScroll:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat offsetX=scrollView.contentOffset.x;
    offsetX+=scrollView.frame.size.width*0.5;
    
    //因为最前面还有一个imgView
    int page=offsetX/scrollView.frame.size.width-1;
    self.pageControl.currentPage=page;
    
}

此方法用来计算 contentOffset 对应的 pageControl 的 page ,需要注意的是在第一张图片之前还有最后一张图片,所以计算的时候需要-1

2.scrollViewWillBgeinDragging:

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.timer invalidate];
    self.timer=nil;
}

在scrollView即将被划动时,取消自动轮播,将timer设置为nil

3.scorllViewDidEndDragging: willDecelearate:

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    self.timer=[NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(scrollImage) userInfo:nil repeats:YES];
    
    //优先级 设置到当前的runloop中
    NSRunLoop *runloop=[NSRunLoop currentRunLoop];
    [runloop addTimer:self.timer forMode:NSRunLoopCommonModes];
}

在将要结束划动的时候,重新设置timer 并添加到当前的runloop中


实现轮播图的核心代码

对 contentOffset 的监听

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    
    if([keyPath isEqualToString:@"contentOffset"]){
        //[change objectForKey:NSKeyValueChangeNewKey] 是一个对象
        CGPoint offset= [[change objectForKey:NSKeyValueChangeNewKey] CGPointValue];
        //当划到3后面的1时
        if(offset.x >= self.scrollView.contentSize.width-self.scrollView.frame.size.width){
            [self.scrollView setContentOffset:CGPointMake(self.scrollView.frame.size.width, 0)];
            self.pageControl.currentPage=0;
        }
        //当划到1前面的3时
        else if(offset.x <= 0){
            [self.scrollView setContentOffset:CGPointMake(self.scrollView.contentSize.width-2*self.scrollView.frame.size.width, 0)];
            self.pageControl.currentPage=self.pageControl.numberOfPages-1;
        }
    }
    
}

首先[change objectForKey:NSKeyValueChangeNewKey] 是一个对象,我们可以通过  CGPointValue 去得到contentOffset

然后我们对 contentOffset 的 x 进行判断,如果在最后一张图片,即3后面的1时,将scrollView的contentOffset 设置为初始的1所在的位置,这里不能设置动画

同理,如果在1前面的3时,将scrollView的contentOffset 设置为初始的3所在的位置,这里不能设置动画

需要注意 pageControl 的设置也应该实时设置

最后,我们将自己轮播的方法 scrollImage 填写

-(void)scrollImage{
            
    NSInteger page=[self.pageControl currentPage];
    page++;
    CGFloat offsetX= page * self.scrollView.frame.size.width+self.scrollView.frame.size.width;
    
    [self.scrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
}

从当前的 page 滚动至下一个 page ,设置动画

至此我们完成了支持滑动和自己定时播放的简单页面的轮播图