无法使用Swift显示多个UICollectionViewCells

时间:2017-11-10 14:37:17

标签: ios swift uicollectionview uicollectionviewcell

尽管将第二个单元格注册到collectionView,但我无法显示第二个单元格。有谁知道为什么会这样?单元格存在,就像我切换另一个单元格显示的行一样。

class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {


    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView?.backgroundColor = UIColor.white


        collectionView?.register(HeaderCell.self, forCellWithReuseIdentifier: "HeaderCell")
        collectionView?.register(SummaryCell.self, forCellWithReuseIdentifier: "SummaryCell")


    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        }
        return 1
    }

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

        if (indexPath.row == 0) {

            let cell1 = collectionView.dequeueReusableCell(withReuseIdentifier: "HeaderCell", for: indexPath) as! HeaderCell

            return cell1

        } else {
            let cell2 = collectionView.dequeueReusableCell(withReuseIdentifier: "SummaryCell", for: indexPath) as! SummaryCell

            return cell2
        }

    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        return CGSize(width: view.frame.width, height: 200)

    }

}

我看了this,但仍无法让它发挥作用。

P.S。我正在以编程方式编程所有内容。

2 个答案:

答案 0 :(得分:4)

您已注册2个单元格,但只返回1行。请尝试返回2个项目。

//numberOfItemsInSection
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        return 2
    }

答案 1 :(得分:0)

没有一个答案正确/完全解决了这个问题。但是,我确实使用了一些建议,通过添加以下内容使其正常工作:

override func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 2
}

indexPath.row更改为indexPath.section

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

    if (indexPath.section == 0) {

        let cell1 = collectionView.dequeueReusableCell(withReuseIdentifier: "HeaderCell", for: indexPath) as! HeaderCell

        return cell1

    } else {
        let cell2 = collectionView.dequeueReusableCell(withReuseIdentifier: "SummaryCell", for: indexPath) as! SummaryCell

        return cell2
    }
}