繁体   English   中英

UICollectionView.reloadData()在添加第一个项目后起作用,然后似乎在后面运行了一个

[英]UICollectionView.reloadData() works after adding first item, then seems to run one behind

我有一个带有字符串数组的空UICollectionView作为数据源。

当我将第一个字符串添加到数组中并在collectionView上调用reloadData()时,它将按我期望的那样工作。 当我添加第二个字符串并调用reloadData()时,什么也没发生,但是我的数组肯定增加了。 当我添加第三项并调用reloadData()时,第二项出现,但第三项没有出现。 每个新添加项都会导致出现先前的字符串。

如果然后我在不添加字符串的情况下调用reloadData(),则最后一项出现。

我添加到集合的代码:

func addKeyword(keyword: String) {

    keywords.append(keyword)
    newKeywordText.text = ""
    keywordCollection.reloadData()

}

和我的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
}

我知道numberOfItemsInSection返回正确的计数,所以我不知道为什么它采用这种方式。 有任何想法吗?

尝试先完成阵列填充,完成后再调用keywordCollection.reloadData()

您还能分享一下如何调用addKeyword方法吗

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM