Swift轮播图

最近在学习swift,就用swift实现轮播图来练习一下

轮播图的创建有两种方式:
    1>可以用scrollview创建3个view,自己实现循环利用
    2>利用collectionView由系统来处理item的循环利用问题

显然使用collectionView实现的方式比较简单。

轮播图由两部分组成,collectionView和一个pageControl。自定义一个CarouselView,懒加载创建collectionView和pageControl:

fileprivate lazy var carouselCollectionView : UICollectionView = { [unowned self] in
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = UICollectionViewScrollDirection.horizontal//横向滚动
        layout.itemSize = CGSize(width: kViewWidth, height: kViewHeight)
        layout.minimumLineSpacing = 0//行间距为0
        let carouselCollectionView:UICollectionView = UICollectionView(frame: self.bounds, collectionViewLayout: layout)
        carouselCollectionView.showsHorizontalScrollIndicator = false
        carouselCollectionView.isPagingEnabled = true//按页滚动
        carouselCollectionView.backgroundColor = UIColor.white
        carouselCollectionView.register(CarouselCollectionViewCell.self, forCellWithReuseIdentifier: CellIdentifier)//注册自定义cell
        //添加代理
        carouselCollectionView.dataSource = self
        carouselCollectionView.delegate = self
        return carouselCollectionView
    }()
    
    fileprivate lazy var pageControl : UIPageControl = {
        let pageControl:UIPageControl = UIPageControl()
        pageControl.translatesAutoresizingMaskIntoConstraints = false//用代码为pageControl添加NSLayoutConstraint的时候,需要设置
        pageControl.numberOfPages = 1
        return pageControl
    }()

重写自定义视图的初始化方法

init(Y: CGFloat,H:CGFloat) {
        kViewHeight = H
        super.init(frame: CGRect(x: 0, y: Y, width: kViewWidth, height: kViewHeight))
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

使用extension为CarouselView添加一个布局方法

//MARK:- setup UI
extension CarouselView {
    func setupUI() {
        self.addSubview(carouselCollectionView)
        self.addSubview(pageControl)
        //将pageControl添加到自定义视图后,给pageControl添加约束
        let rightConstraint:NSLayoutConstraint = NSLayoutConstraint(item: pageControl, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1.0, constant: -10)
        let bottomConstraint:NSLayoutConstraint = NSLayoutConstraint(item: pageControl, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: -5)
        let heightConstraint:NSLayoutConstraint = NSLayoutConstraint(item: pageControl, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 20)
        pageControl.superview?.addConstraint(rightConstraint)
        pageControl.superview?.addConstraint(bottomConstraint)
        pageControl.superview?.addConstraint(heightConstraint)
    }
}

创建一个数组用来存储自定义CarouselModel

var carouselModelArr : [CarouselModel]? {
        didSet {
            //数组发生变化时刷新collectionView
            self.carouselCollectionView.reloadData()
            pageControl.numberOfPages = carouselModelArr?.count ?? 0
            //初识时,让collectionView滚动到中间某个位置,使用户可以向前翻页
            let index = (carouselModelArr?.count ?? 0)*10
            self.carouselCollectionView.scrollToItem(at: IndexPath(item: index, section: 0), at: .left, animated: false)
            //添加计时器
            removeTimer()
            addTimer()
        }
    }

自定义一个CarouselModel用来接收数据

class CarouselModel: NSObject {

    var title:String = ""
    var pic_url:String = ""
    
    init(dic:[String:NSObject]) {
        super.init()
        //kvc方法,字典转模型
        setValuesForKeys(dic)
    }
    //获取的数据中没定义的键值在这里处理
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
//        print("undefined key : \(key), value : \(value)")
    }
}

创建自定义cell
自定义 cell包括两部分:
1>展示图片用的imageView
2>展示文字title的Label

import UIKit
import SDWebImage

class CarouselCollectionViewCell: UICollectionViewCell {
    
    var imageView = UIImageView()
    
    var titleLabel = UILabel()
    
    var carouselModel : CarouselModel? {
        didSet {
            //设置属性时给label和imageView赋值
            titleLabel.text = carouselModel?.title
            //使用SDWebImage设置imageView图片
            imageView.sd_setImage(with: URL(string: (carouselModel?.pic_url ?? "")!), placeholderImage: UIImage(named: "placehold"))
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension CarouselCollectionViewCell {
    func setupUI() {
        imageView.frame = self.bounds
        titleLabel.frame = CGRect(x: 0, y: self.bounds.size.height - 30, width: self.bounds.size.width, height: 30)
        titleLabel.backgroundColor = UIColor(white: 0.4, alpha: 0.3)
        titleLabel.textColor = .white
        self.addSubview(imageView)
        self.addSubview(titleLabel)
    }
}

自定义CarouselView遵循 DataSource 协议

//MARK:- collectionViewDataSource
extension CarouselView : UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //返回10000倍item实现无限轮播,因为collectionView的重用机制,并不会创建这么多item,不用担心内存问题
        return 10000*(carouselModelArr?.count ?? 0);
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        //使用自定义item:CarouselCollectionViewCell
        let collectionItem = collectionView.dequeueReusableCell(withReuseIdentifier: CellIdentifier, for: indexPath) as! CarouselCollectionViewCell
        let index = indexPath.item % carouselModelArr!.count
        collectionItem.carouselModel = carouselModelArr![index]
        return collectionItem
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let item = collectionView.cellForItem(at: indexPath) as! CarouselCollectionViewCell
        print("title : \(item.titleLabel.text)")
    }
}

自定义CarouselView遵循Delegate协议

//MARK:- collectionViewDelegate
extension CarouselView : UICollectionViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //当偏移超过page的一半时pageControl调到下一个
        let offset = scrollView.contentOffset.x + kViewWidth / 2
        pageControl.currentPage = Int(offset / kViewWidth) % (carouselModelArr?.count ?? 1)
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        //用户开始拖拽时,移除定时器
        removeTimer()
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        //用户停止拖拽时,打开定时器
        addTimer()
    }
}

添加计时器,使collection View滚动起来

//MARK:- 添加计时器
extension CarouselView {
    func addTimer() {
        timer = Timer(timeInterval: 3.0, target: self, selector: #selector(scrollToNextPage), userInfo: nil, repeats: true)
        RunLoop.main.add(timer!, forMode: .commonModes)
    }
    
    func removeTimer() {
        timer?.invalidate()
        timer = nil
    }
    
    func scrollToNextPage() {
        let offsetX = carouselCollectionView.contentOffset.x + kViewWidth//当前偏移量加上一页的宽度
        carouselCollectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true)
        
    }
}

此时,一个简单的轮播图就完成了!

下面是轮播图的使用:

import UIKit
import AFNetworking

class ViewController: UIViewController {
    //创建自定义carousView
//    let carouselView = CarouselView(Y: 64, H: 200)//需要毛玻璃效果时Y为64
    let carouselView = CarouselView(Y: 0, H: 200)//不需要毛玻璃效果时Y,为0。

    var modelArr = [CarouselModel]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        getArrayFromWeb()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

extension ViewController {
    func setupUI() {
//        self.automaticallyAdjustsScrollViewInsets = false//需要毛玻璃效果时设置(是否根据所在界面的navigationbar与tabbar的高度,自动调整scrollview的inset.默认是true)
        self.navigationController?.navigationBar.isTranslucent = false//不需要毛玻璃效果时设置
        self.view.addSubview(carouselView)
    }
    //使用AFN解析数据
    func getArrayFromWeb() {
        let manager = AFHTTPSessionManager()
        manager.get("http://www.douyutv.com/api/v1/slide/6", parameters: ["version" : "2.300"], progress: nil, success: { (task:URLSessionDataTask, json:Any) in
//            print("jsonData: \(json)")
            guard let dataDic = json as? [String : NSObject] else { return }
            guard let dataArr = dataDic["data"] as? [[String : NSObject]] else { return }
            for dic in dataArr {
                self.modelArr.append(CarouselModel(dic: dic))
            }
            //获取完数据,将数组赋给carouselView的carouselModelArr
            self.carouselView.carouselModelArr = self.modelArr
        }) { (task:URLSessionDataTask?, error:Error) in
            print("error : \(error)")
        }
    }
}

GitHub地址

你可能感兴趣的:(Swift轮播图)