Swift应用案例 1.无限轮播

从今天开始,我学习的重点开始转向Swift,并且会分享一些自己学习的心得体会,今天给大家带来的的是无限轮播。广告页的无限轮播是非常常见的一个功能,大多数APP都有,大多数程序员也都实现过,今天我们用Swift实现一下。项目地址
  图片切换我们可以选择的基本控件有两个UIScrollView 和 UICollectionView,这次我们选择UICollectionView;既然是轮播,就会用到Timer。所以,我们这次主要应用的知识点为UICollectionView 和 Timer;

import UIKit

class CycleScrollView: UIView, UICollectionViewDelegate,UICollectionViewDataSource {

    var bottomView : UICollectionView?
    var width : CGFloat?
    var height : CGFloat?
    var timer : Timer?
    
    override init(frame: CGRect){
        
        super.init(frame: frame)
        // 1.设置背景色
        self.backgroundColor = UIColor.clear
        // 2.设置宽高
        width = self.frame.size.width
        height = self.frame.size.height
        // 3.添加bottomView
        setupBottomView()
        // 4.添加定时器
        setupTimer()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func setupBottomView() {
        
        // 5.设置collectionView的布局
        let flowLayout = UICollectionViewFlowLayout();
        flowLayout.itemSize = self.bounds.size
        flowLayout.minimumLineSpacing = 0;
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.scrollDirection = UICollectionViewScrollDirection.horizontal;
        bottomView = UICollectionView.init(frame: self.bounds, collectionViewLayout: flowLayout)
        self.addSubview(bottomView!);
        // 6.设置collectionView的尺寸
        bottomView?.contentSize = CGSize(width:width! * CGFloat(4),height:height!)
        // 7.分页
        bottomView?.isPagingEnabled = true
        // 8.去掉滚动条
        bottomView?.showsVerticalScrollIndicator = false
        bottomView?.showsHorizontalScrollIndicator = false
        // 9.设置代理
        bottomView?.delegate = self
        bottomView?.dataSource = self
        // 10.注册cell
        bottomView?.register(UICollectionViewCell().classForCoder, forCellWithReuseIdentifier: "ID");
        if #available(iOS 10.0, *) {
            // 11.预加载
            bottomView?.isPrefetchingEnabled = true
        } else {
            // Fallback on earlier versions
        }
    }
    func setupTimer() {
        // 12.实例化定时器
        timer = Timer.init(timeInterval: 2, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true);
        RunLoop.main.add(timer!, forMode: RunLoopMode.defaultRunLoopMode);

        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
        
            self.timer?.fire();
        }
    }
    func timerAction() {
        
        var contentOffsetX = (self.bottomView?.contentOffset.x)! + self.frame.size.width
        
        if contentOffsetX > self.frame.size.width * 3  {
            // 当前视图显示的是第三个的时候,设置bottomView的偏移量为0
            self.bottomView?.contentOffset = CGPoint(x:0,y:0)
            contentOffsetX = self.frame.size.width
        }
         self.bottomView?.setContentOffset(CGPoint(x:contentOffsetX,y:0), animated: true)
    }
    // 重写removeFromSuperview方法,用于删除定时器,否则定时器一直存在,浪费内存
    override func removeFromSuperview() {
        
        timer?.invalidate()
        timer = nil
        super.removeFromSuperview()
    }
    // Mark:UICollectionViewDataSource
    // 设置Itmes
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return 4;
    }
    // 设置cell
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell : UICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "ID", for: indexPath)
        for view : UIView in cell.contentView.subviews {
            
            view.removeFromSuperview()
        }
        let imageView = UIImageView.init(frame: cell.contentView.bounds)
        if indexPath.row < 3 {
            
            imageView.image = UIImage.init(named: String(indexPath.row))

        } else {
           imageView.image = UIImage.init(named: String(0))
        }
        cell.contentView.addSubview(imageView)
        
        return cell;
    }
    // Mark:UICollectionViewDelegate
    // 点击方法
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        print("您点击了第 \(indexPath.row == 3 ? 0 : indexPath.row) 个");
    }
    
}

UICollectionView 和 Timer的用法和OC基本相同。Swift和OC的UI部分应该是一致的,因为底层都是OpenGL。我直接说一下区别:
1.Timer:如果重复,OC是等一个间隔再执行的,Swift是立即执行的,所以我用了GCD延时开启定时器。
2.Swift 没有 CGPointZero。
  无限轮播的原理就是在最后面多添加一个和第一个相同的itme。当你滑动到最后一个itme时,把UICollectionView的contentOffset置零,继续向右活动。如果不添加,会给用户一种卡顿的感觉。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,252评论 4 61
  • 慧语禅心:沉迷梦中,追逐名利,你争我夺 你看看这个世界,大家都沉迷在梦中,追逐名利,你争我夺,你好,我要比你更好,...
    xcy无名阅读 285评论 0 0
  • 在微博上看到一则动人的新闻:单亲妈妈花29年把重度脑瘫儿送进哈佛。照片里,妈妈和高材生的脑瘫儿子笑得都很灿烂。 2...
    周婧sculptor阅读 996评论 0 10
  • 旭同学的暑假过去一半,我的倒计时剩下五十天,作为犒赏,相伴去听了一场音乐会,不过是坐在“山上”。 我问王老师,坐“...
    木徒阅读 230评论 0 0
  • 我想做自己喜欢的事情,不在乎别人怎么看,怎么说
    韩灰灰阅读 163评论 0 0