背景是,黑色,,细胞是,白色,,尽管没有一个细胞显示在simulator?
中,有人知道为什么会这样吗?
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)
}
}
发布于 2017-07-27 04:37:27
更新:
以编程方式初始化ChatLog视图控制器,如下所示,这意味着不调用UICollectionView数据源方法,例如不调用collectionView(_:cellForItemAt:)
。
let newViewController = ChatLog(collectionViewLayout: UICollectionViewLayout())
用替换此
let newViewController = ChatLog(collectionViewLayout: UICollectionViewFlowLayout())
--
由于您已经声明了一个UICollectionViewController
,所以实际上不需要在代码中显式地设置集合视图的delegate
和dataSource
属性。
只需确保在Main.storyboard
中,单击视图控制器,然后单击标识检查器,就可以将UICollectionViewController
的类设置为ChatLog。还要确保您已经单击了UICollectionViewCell
并将其标识符设置为"cellId“。
如果这是一个多视图控制器项目,请确保可以通过使其成为初始视图控制器或从另一个视图控制器对此视图控制器提供segue/导航来导航到ChatLog视图控制器。
下面的图片概述了我的解决方案。
发布于 2017-07-27 04:24:48
设置delegate
和collectionView
的数据源。datasource
和delegate
方法(numberOfItemsInSection
、cellForItemAtIndexpath
等)只有在设置了delegate
和datasource
之后才会被调用。您可以在代码或情节提要中设置它(如果您使用了故事板来设计collectionView
)
在viewDidLoad
中,您可以添加
collectionView.delegate = self
collectionView.datasource = self
https://stackoverflow.com/questions/45350717
复制