swift - 以编程方式使 UICollectionViewController 不显示单元格

标签 swift uicollectionview

背景是黑色,单元格是白色,尽管模拟器中没有显示任何单元格?谁知道为什么会这样可能是?

import UIKit
import Foundation

class ChatLog: UICollectionViewController, UITextFieldDelegate, UICollectionViewDelegateFlowLayout {

    let cellId = "cellId"

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView?.backgroundColor = UIColor.black
        collectionView?.register(UICollectionViewCell.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)
        cell.backgroundColor = UIColor.white

        return cell
    }

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

}

最佳答案

更新:

如下所示以编程方式初始化 ChatLog View Controller 意味着不会调用 UICollectionView 数据源方法,例如 collectionView(_:cellForItemAt:) 不会被调用。

let newViewController = ChatLog(collectionViewLayout: UICollectionViewLayout())

替换为这个:

让 newViewController = ChatLog(collectionViewLayout: UICollectionViewFlowLayout())

--

因为您已经声明了一个 UICollectionViewController,您实际上不需要在代码中显式设置您的 delegatedataSource 属性 Collection View 。

只需确保在 Main.storyboard 中,您已通过单击 View Controller 然后单击身份检查器将 UICollectionViewController 的类设置为 ChatLog。还要确保您已单击 UICollectionViewCell 并将其标识符设置为“cellId”。

如果这是一个多 View Controller 项目,请确保可以通过将其设为初始 View Controller 或从另一个 View Controller 提供到该 View Controller 的 segue/导航来导航到 ChatLog View Controller 。

下面的图片概述了我的解决方案。

Storyboard Cell

Storyboard UICollectionViewController ChatLog

关于swift - 以编程方式使 UICollectionViewController 不显示单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45350717/

相关文章:

ios - 应用程序在 iPhone 6s 的 'peek and pop' 实现中卡住

ios - 在 UICollectionView 中显示错误的图像

ios - RestKit删除孤立对象规则

ios - 获取 UITesting Xcode 7 中表格每个部分的行数

ios - 使用 Swift 3.0 调用 Google Cloud Natural Language API

ios - 如何在 CollectionView iOS 中停止自动重新加载和刷新图像

ios - UICollectionView AutoSizingCells 在 reloadData() 上出现奇怪的跳跃/故障

ios - Swift CollectionViewCell 的框架与其 CollectionView 不同

ios - 放置 UICollectionView 以创建 2x3 网格 iOS 的问题

swift - 在 Swift 中十进制、二进制和十六进制之间转换