Swift collectionViewCells没有显示

时间:2017-04-01 08:44:48

标签: swift uicollectionview

我有这个Swift代码 `

let cellId="cellId"

class FeedController: UICollectionViewController{
override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.title = "Centill"

    collectionView?.reloadData()
    collectionView?.backgroundColor = UIColor(white: 0.95, alpha: 1)
    collectionView?.register(FeedCell.self, forCellWithReuseIdentifier: cellId)
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 3
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell=collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath);
    cell.backgroundColor = .yellow
    return cell
}

}

class FeedCell: UICollectionViewCell {

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

    setupViews()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
func setupViews(){
    backgroundColor = .yellow
}
}

` 但不幸的是我的单元格没有显示。它只显示导航栏和背景颜色。我的代码可能有什么问题?

4 个答案:

答案 0 :(得分:0)

试试吧。 你在课堂上添加

UICollectionViewDataSource and UICollectionVIewDelegate.

答案 1 :(得分:0)

尝试此代码:

    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
    layout.itemSize = CGSize(width: 60, height: 60)

    let myCollectionView:UICollectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
    myCollectionView.dataSource = self
    myCollectionView.delegate = self
    myCollectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")
    myCollectionView.backgroundColor = UIColor.whiteColor()
    self.view.addSubview(myCollectionView)

答案 2 :(得分:0)

在您的cellForItemAt dataSource方法中,您需要提供自定义UICollectionCell类

let cell=collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! FeedCell
cell.backgroundColor = .yellow
return cell

然后你就能看到细胞。

答案 3 :(得分:0)

您必须提供集合视图单元格的大小。添加以下代码段

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    // calculate and return the height
}