Alk
Alk

Reputation: 5567

Populating UICollectionView Not Working

I am trying to populate a collectionView with the following code, however it is always empty. I can't figure out what the issue is. Here is the variables after the self.collectionView.reloadData() line is executed: :

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
}

Upvotes: 0

Views: 250

Answers (1)

Kelvin Lau
Kelvin Lau

Reputation: 6781

UICollectionView needs to know where the dataSource and delegate is.

Add these two lines in viewDidLoad:

collectionView.dataSource = self
collectionView.delegate = self

Alternatively, you could use a didSet observer to cluster that functionality together with the collectionView declaration, which is what I usually do:

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

Upvotes: 2

Related Questions