ios - 使用代码创建 UICollectionView 需要的步骤

iSwift

2018-03-28T11:04:06Z||2018-03-28T11:06:26Z

支持Swift 4. 类似这样:

class MyViewController {
    // 常量
    let CellIdentifier = "MyViewControllerCell"
    let CellWidth = CGFloat(116.0)
    let CellHeight = CGFloat(60.0)
  
    var collectionView: UICollectionView!
    var items = [String]()
  
    override func viewDidLoad() {
        super.viewDidLoad()
      
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: CellWidth, height: CellHeight)

        collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.register(MyViewControllerCell.self, forCellWithReuseIdentifier: CellIdentifier)
        collectionView.backgroundColor = UIColor.white
        collectionView.dataSource = self
        collectionView.delegate = self
        addSubview(collectionView)
    }
}

// MARK: - UICollectionViewDataSource
extension MyViewController: UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView,
                                 numberOfItemsInSection section: Int) -> Int {
        return items.count
    }
    
    func collectionView(_ collectionView: UICollectionView,
                                 cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CellIdentifier,
                                                      for: indexPath) as! MyViewControllerCell
        // 配置 Cell
        return cell
    }
}

// MARK: - UICollectionViewDelegate
extension MyViewController: UICollectionViewDelegate {

}

// MARK: - UICollectionViewDelegateFlowLayout
extension MyViewController: UICollectionViewDelegateFlowLayout {
}