[英]UICollectionView.reloadData() works after adding first item, then seems to run one behind
I have an empty UICollectionView with an array of strings as the datasource. 我有一个带有字符串数组的空UICollectionView作为数据源。
When I add the first string to the array and call reloadData() on the collectionView this works as I would expect. 当我将第一个字符串添加到数组中并在collectionView上调用reloadData()时,它将按我期望的那样工作。 When I add a second string and call reloadData() nothing happens, but my array has definitely grown. 当我添加第二个字符串并调用reloadData()时,什么也没发生,但是我的数组肯定增加了。 When I add a third item and call reloadData(), the second item appears but not the third. 当我添加第三项并调用reloadData()时,第二项出现,但第三项没有出现。 Each new addition results in the previous string appearing. 每个新添加项都会导致出现先前的字符串。
If I then call reloadData() without adding a string, the last item then appears. 如果然后我在不添加字符串的情况下调用reloadData(),则最后一项出现。
My code for adding to the collection: 我添加到集合的代码:
func addKeyword(keyword: String) {
keywords.append(keyword)
newKeywordText.text = ""
keywordCollection.reloadData()
}
And my collectionView relevant code: 和我的collectionView相关的代码:
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. 我知道numberOfItemsInSection返回正确的计数,所以我不知道为什么它采用这种方式。 Any ideas? 有任何想法吗?
Try to complete your array population first, and when it is completed then call keywordCollection.reloadData() 尝试先完成阵列填充,完成后再调用keywordCollection.reloadData()
can you also share on how you are calling the addKeyword method 您还能分享一下如何调用addKeyword方法吗
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.