美文网首页iOS Developer
iOS 轮播图(三个UIImageView轮播)

iOS 轮播图(三个UIImageView轮播)

作者: 杯水救车薪 | 来源:发表于2017-09-07 18:11 被阅读565次

    提到app轮播图,我们会想到好多种实现方法。这里我给大家介绍一下用三个UIImageView创建轮播图的方法,这里主要对思路做讲解具体代码请查看文章末尾的demo。
    1.首先创建UIScrollView,和三个UIimageView。这里我用了懒加载的方式,一定要将imageView的frame分配好。

    - (UIImageView *)centerImageView {
        if (!_centerImageView) {
            _centerImageView = [[UIImageView alloc]initWithFrame:CGRectMake(kwidth, 0, kwidth, kheight)];
            [_centerImageView.layer setMasksToBounds:YES];
            _centerImageView.contentMode = UIViewContentModeScaleAspectFill;
            _centerImageView.backgroundColor = [UIColor whiteColor];
        }
        return _centerImageView;
    }
    
    - (UIImageView *)LeftImageView {
        if (!_LeftImageView) {
            _LeftImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kwidth, kheight)];
            [_LeftImageView.layer setMasksToBounds:YES];
            _LeftImageView.contentMode = UIViewContentModeScaleAspectFill;
    
            _LeftImageView.backgroundColor = [UIColor whiteColor];
        }
        return _LeftImageView;
    }
    
    - (UIImageView *)rightImageView {
        if (!_rightImageView) {
            _rightImageView = [[UIImageView alloc] initWithFrame:CGRectMake(2 * kwidth, 0, kwidth, kheight)];
            [_rightImageView.layer setMasksToBounds:YES];
            _rightImageView.contentMode = UIViewContentModeScaleAspectFill;
    
            _rightImageView.backgroundColor = [UIColor whiteColor];
        }
        return _rightImageView;
    }
    
    - (UIScrollView *)scroll {
        if (!_scroll) {
            _scroll = [[UIScrollView alloc] initWithFrame:self.bounds];
            
            _scroll.backgroundColor=[UIColor whiteColor];
            _scroll.showsHorizontalScrollIndicator=NO;
            _scroll.showsVerticalScrollIndicator=NO;
            _scroll.pagingEnabled=YES;
            _scroll.bounces=NO;
            _scroll.delegate=self;
            _scroll.contentOffset=CGPointMake(kwidth, 0);
            _scroll.contentSize=CGSizeMake(kwidth*3, 0);
            [_scroll addSubview:self.LeftImageView];
            
            [_scroll addSubview:self.centerImageView];
            
            [_scroll addSubview:self.rightImageView];
        }
        
        return _scroll;
    }
    

    用initWithFrame:(CGrect)frame方法初始化

    - (instancetype) initWithFrame:(CGRect)frame {
        
        self = [super initWithFrame:frame];// 先调用父类的initWithFrame方法
        if (self) {
            
            [self addSubview:self.scroll];
    
    
            self.pageControl=[[UIPageControl alloc]initWithFrame:CGRectMake((kwidth - 60)/2, kheight - 20, 60, 20)];
            self.pageControl.currentPageIndicatorTintColor=[UIColor whiteColor];
            self.pageControl.pageIndicatorTintColor=[UIColor colorWithWhite:0 alpha:0.8];
            
            self.currentIndex = 0;
            
            
        }
            return self;
    }
    
    

    设置完成后创建定时器,设置轮播时间。定时器的模式要选择NSRunLoopCommonModes。repeat设为YES

    self.timer = [HWWeakTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(autoScroll) userInfo:nil repeats:YES];
                [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    

    autoScroll中只需实现这一句代码就可以了,也就是说实际上的轮播效果就是从第二个以动画的形式移动到第三个。再以非动画的形式将其移动回来。

    - (void) autoScroll {
        [self.scroll setContentOffset:CGPointMake(2 * kwidth, 0) animated:YES];
        
    }
    

    当调用autoScroll方法是,同时会触发scrollView的代理方法,根据方法名可以知道当setContentOffset方法的动画效果结束时会调用该代理方法,接下来就是重头戏了

    #pragma mark ----UIScrollViewDelegate代理方法(停止加速时调用)
    
    - (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
        [self refreshImage];
        self.scroll.contentOffset = CGPointMake(kwidth,0);
    
    }
    

    刷新三个imageView的图片,举例:如果有三张图片分别为2、0、1,对应imageView的left,center,和right.第一次调用autoScroll,先以动画的形式有center移动到right。当动画停止时,通过计算,将left,center,right分别对应为0、1、2,然后以非动画的形式(self.scroll.contentOffset = CGPointMake(kwidth,0))将center移动回来。之后每调用一次sutoScroll都会执行一次上述步骤,这样就形成了视觉上的轮播效果。这样轮播也就初具模型了。

    -(void)refreshImage
    {
        if (self.scroll.contentOffset.x > kwidth) {
            
            self.currentIndex=((self.currentIndex + 1) % self.imageCount);
        }
        else if(self.scroll.contentOffset.x < kwidth){
    //        防止currentIndex为0时,数组越界
            self.currentIndex=((self.currentIndex - 1 + self.imageCount) % self.imageCount);
        }
        [self setImageByIndex:(int)self.currentIndex array:self.imageArray];
    }
    #pragma mark ----该方法根据传回的下标设置三个ImageView的图片,如果是网络图片可以在这里进行修改
    -(void)setImageByIndex:(int)currentIndex array:(NSArray *)array
    {
        if (!array.count) {
            [self.timer invalidate];
            self.timer = nil;
    
            return;
        }
            NSString *currentImageName=[NSString stringWithString:array[currentIndex]];
            
            self.centerImageView.image = [UIImage imageNamed:currentImageName];
            self.centerImageView.tag = currentIndex;
            self.centerImageView.userInteractionEnabled = YES;
            [self.centerImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imgViewClick:)]];
            
            NSString *LeftString = array[((self.currentIndex - 1 + self.imageCount) % self.imageCount)];
            self.LeftImageView.image = [UIImage imageNamed:LeftString];
            
            NSString *rightString = array[((self.currentIndex + 1) % self.imageCount)];
            
            self.rightImageView.image = [UIImage imageNamed:rightString];
            
            self.pageControl.currentPage=currentIndex;
        
        
       
        
    }
    
    #pragma mark - banner点击事件
    -(void)imgViewClick:(UITapGestureRecognizer *)recognizer {
        UIImageView *imgView = (UIImageView *)recognizer.view;
        
        if (self.bannerClick) {
            self.bannerClick(imgView.tag);
        }
    }
    
    

    2.然后我们要在拖动时停止自动轮播,放开后重新开启自动轮播。拖动时调用scrollViewWillBeginDragging代理方法停止定时器,同时调用scrollViewDidEndDecelerating代理方法刷新图片。放开后调用scrollViewDidEndDragging代理方法重新添加定时器。笔者试过用 [self.timer setinvalidateDate:[NSDate distantPast]]方法停止和开启定时器,但是效果并不好。所以还是用比较土的方法。

    #pragma mark -- 拖拽停止NSTimer
    - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    
        [self.timer invalidate];
        self.timer = nil;
        
    }
    
    - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
    {
        [self refreshImage];
        self.scroll.contentOffset = CGPointMake(kwidth,0);
    }
    
    - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    //    这里不建议使用 [self.timer setinvalidateDate:[NSDate distantPast]]方法
        if (self.second != 0) {
            NSTimeInterval interval = fabs(self.second);
            self.timer = [HWWeakTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(autoScroll) userInfo:nil repeats:YES];
            [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
        }
    

    3.最后我们要对性能做一些优化,主要是针对nstimer 循环引用的。

    轮播图demo

    相关文章

      网友评论

        本文标题:iOS 轮播图(三个UIImageView轮播)

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