Swift collectionView 单元格未显示

标签 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
}
}

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

最佳答案

试试这个代码:

    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)

关于Swift collectionView 单元格未显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43154691/

相关文章:

ios - UITableViewCell 无法根据它包含的动态 CollectionView 调整高度

swift - 如何使用代码注释画线?

ios - 如何删除添加到特定相册但不添加到其他相册的照片?

xcode - Xcode beta 7.3 (7D162j) 中的 UIFont 错误?

ios - "No Challenges"消息游戏中心 iOS 8

swift - 在 Swift 中,如何将字符串值分配给另一个类中的属性?

ios - 自动调整 UICollectionView 高度以调整其内容大小

ios - UICollectionView - 如何使用一个单元格的更改更新所有单元格

ios - Swift:旋转后 Collection View 改变布局

ios - UICollectionView 的水平流