填充UICollectionView不起作用

时间:2016-05-27 17:51:50

标签: ios swift uicollectionview

我正在尝试使用以下代码填充collectionView,但它始终为空。我无法弄清楚问题是什么。以下是self.collectionView.reloadData()行执行后的变量::

enter image description here

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
}

1 个答案:

答案 0 :(得分:2)

UICollectionView需要知道 dataSourcedelegate

viewDidLoad中添加这两行:

collectionView.dataSource = self
collectionView.delegate = self

或者,您可以使用didSet观察者将该功能与collectionView声明一起聚类,这就是我通常所做的事情:

@IBOutlet private var collectionView: UICollectionView! { didSet {
  collectionView.dataSource = self
  collectionView.delegate = self
}