Vahid
Vahid

Reputation: 3496

How to dynamically add a cell to UICollectionView

I want to add a cell in UICollectionCell on run time. What is the best way that not affected performances?

And It's my sample cell class:

class PersonViewCell: UICollectionViewCell {
    @IBOutlet weak var coverImg: UIImageView!
    @IBOutlet weak var nameLbl: UILabel!
    @IBOutlet weak var titleLbl: UILabel! 

    var p: Person!    

    func configureCell(p: Person) {
        self.titleLbl = p.title
        nameLbl.text = p.name
        coverImg.image = UIImage(named: "image-not-available")     
    }

}

Upvotes: 0

Views: 5877

Answers (1)

Ollie
Ollie

Reputation: 1946

Make a new instance variable in your class to store an array and save your JSON results to it. Then use that to return the number of cells in numberOfItemsInSection, and draw the cells in cellForItemAtIndexPath. If you want to update after that, just call collection.reloadData()

Also, assuming you're making your network request on a background thread, make sure you call collection.reloadData() on the main.

Upvotes: 2

Related Questions