我正在尝试使用以下代码填充collectionView,但它始终为空。我无法弄清楚问题是什么。以下是self.collectionView.reloadData()
行执行后的变量::
import UIKit
class SingleChatFull: UIViewController,UICollectionViewDelegate, UICollectionViewDataSource, openUserChat {
var chat_m = [Message]()
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
collectionView.backgroundColor = UIColor.whiteColor()
// Do any additional setup after loading the view.
}
func canOpenUserChat(messages: [Message]) {
chat_m = messages
dispatch_async(dispatch_get_main_queue()) {
self.collectionView.reloadData()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return chat_m.count
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("message_cell" , forIndexPath: indexPath) as! DisplayMessageCollectionViewCell
cell.messageTextView.text = chat_m[indexPath.row].text
cell.backgroundColor = UIColor.blueColor()
return cell
}
答案 0 :(得分:2)
UICollectionView
需要知道 dataSource
和delegate
。
在viewDidLoad
中添加这两行:
collectionView.dataSource = self
collectionView.delegate = self
或者,您可以使用didSet
观察者将该功能与collectionView
声明一起聚类,这就是我通常所做的事情:
@IBOutlet private var collectionView: UICollectionView! { didSet {
collectionView.dataSource = self
collectionView.delegate = self
}