I have an empty UICollectionView with an array of strings as the datasource.
When I add the first string to the array and call reloadData() on the collectionView this works as I would expect. When I add a second string and call reloadData() nothing happens, but my array has definitely grown. When I add a third item and call reloadData(), the second item appears but not the third. Each new addition results in the previous string appearing.
If I then call reloadData() without adding a string, the last item then appears.
My code for adding to the collection:
func addKeyword(keyword: String) {
keywords.append(keyword)
newKeywordText.text = ""
keywordCollection.reloadData()
}
And my collectionView relevant code:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print("keywords: at refresh \(keywords.count)")
return keywords.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let keyword = keywords[indexPath.row]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "KeywordCloudCell", for: indexPath) as! KeywordCloudCell
let keywordLabel:UILabel = (cell.viewWithTag(1) as? UILabel)!
keywordLabel.text = keyword
return cell
}
I know that numberOfItemsInSection is returning the correct count, so I have no idea why its behaving this way. Any ideas?
Try to complete your array population first, and when it is completed then call
keywordCollection.reloadData()
can you also share on how you are calling the addKeyword method