UICollectionViewController未注册创建的自定义单元类

时间:2018-05-30 03:27:31

标签: ios swift uicollectionviewcell

我正在尝试更改单元格的颜色。我有一个名为HomeController的文件,我在其中布局单元格。我创建了一个名为HomePostCell的自定义单元格。我在HomePostCell注册了HomeController,但没有任何结果。单元格颜色没有变化。我的代码如下所示。

控制器:

import UIKit

class HomeController: UICollectionViewController {
    let cellId = "cellId"

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView?.backgroundColor = .white
        collectionView?.register(HomePostCell.self, forCellWithReuseIdentifier: cellId)
    }

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

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! HomePostCell

        return cell
    }
}

细胞:

import UIKit

class HomePostCell: UICollectionViewCell {
    let photoImageView: UIImageView = {
        let iv = UIImageView()
        iv.backgroundColor = .blue
        return iv
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)

        addSubview(photoImageView)
        photoImageView.anchor(top: topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

我想要出现五个蓝色单元格,但它们不是。

1 个答案:

答案 0 :(得分:-2)

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! HomePostCell
cell.setupData()

return cell
}