繁体   English   中英

为什么我的收藏夹视图单元格没有显示…?

[英]Why aren't my collection view cells showing…?

自从我以编程方式创建集合视图以来已经有一段时间了,我似乎找不到为什么我的单元格没有显示的原因。 正在设置委托和数据源。 正在设置尺寸,并且尺寸不太大。

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    let cellId = "cellId"

    override func viewDidLoad() {
        super.viewDidLoad()

        setupCV()
    }

    var containerCollectionView: UICollectionView = {
        let layout = UICollectionViewLayout()
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = UIColor.white
        return cv
    }()
}

extension ViewController {
    fileprivate func setupCV() {
        // these first two lines add the colelction view and apply constraints - they work and the CV is properly displayed inside the view controller
        self.view.addSubview(containerCollectionView)
        containerCollectionView.anchor(view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)

        containerCollectionView.delegate = self
        containerCollectionView.dataSource = self

        containerCollectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 150, height: 150)
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
        cell.backgroundColor = UIColor.yellow
        return cell
    }

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

您正在初始化错误的布局。

尝试这个:

let layout = UICollectionViewFlowLayout()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM