Swift学习笔记(十二):使用UICollectionView

280 阅读1分钟

使用UICollectionView

import UIKit

class MyBannerView: UIView, UICollectionViewDelegate, UICollectionViewDataSource {


    var dataList = Array<Any>()

    var myCollectionView: UICollectionView?


    override init(frame: CGRect) {

        super.init(frame: frame)
        

        let layout = UICollectionViewFlowLayout()

        layout.itemSize = frame.size

        layout.scrollDirection = .horizontal

        layout.minimumLineSpacing = 0

        layout.minimumInteritemSpacing = 0


        myCollectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height), collectionViewLayout: layout)

        myCollectionView?.dataSource = self

        myCollectionView?.delegate = self

        myCollectionView?.isPagingEnabled = true

        myCollectionView?.showsHorizontalScrollIndicator = false

        myCollectionView?.bounces = false

        myCollectionView?.register(UINib(nibName: "BannerCollectionViewCell", bundle: Bundle.main), forCellWithReuseIdentifier: "BannerCollectionViewCell")

        

        addSubview(myCollectionView!)

    }


    required init?(coder: NSCoder) {

        fatalError("init(coder:) has not been implemented")

    }

    func setDataList(data: Array<Any>) {

        dataList = data

        myCollectionView?.reloadData()

    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        dataList.count

    }


    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BannerCollectionViewCell", for: indexPath) as! BannerCollectionViewCell

        cell.imageView.backgroundColor = indexPath.item % 2 > 0 ? .cyan : .purple

        return cell

    }

}