背景是黑色,单元格是白色,尽管模拟器中没有显示任何单元格?
谁知道为什么会这样可能是?
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
,您实际上不需要在代码中显式设置您的 delegate
和 dataSource
属性 Collection View 。
只需确保在 Main.storyboard
中,您已通过单击 View Controller 然后单击身份检查器将 UICollectionViewController
的类设置为 ChatLog。还要确保您已单击 UICollectionViewCell
并将其标识符设置为“cellId”。
如果这是一个多 View Controller 项目,请确保可以通过将其设为初始 View Controller 或从另一个 View Controller 提供到该 View Controller 的 segue/导航来导航到 ChatLog View Controller 。
下面的图片概述了我的解决方案。
关于swift - 以编程方式使 UICollectionViewController 不显示单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45350717/