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置零,继续向右活动。如果不添加,会给用户一种卡顿的感觉。

posted @ 2017-03-10 13:31  豆丶浆油条  阅读(391)  评论(0编辑  收藏  举报