【问题标题】:UICollectionView.reloadData() works after adding first item, then seems to run one behindUICollectionView.reloadData() 在添加第一项后工作,然后似乎在后面运行
【发布时间】:2017-09-11 22:25:12
【问题描述】:

我有一个带有字符串数组作为数据源的空 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 正在返回正确的计数,所以我不知道它为什么会这样。有什么想法吗?

【问题讨论】:

    标签: ios swift uicollectionview reloaddata


    【解决方案1】:

    尝试先完成数组填充,完成后调用 keywordCollection.reloadData()

    您能否也分享一下您是如何调用 addKeyword 方法的

    【讨论】:

      猜你喜欢
      • 2014-12-06
      • 2022-01-06
      • 2014-01-04
      • 1970-01-01
      • 2022-01-22
      • 2023-03-25
      • 2018-12-11
      • 1970-01-01
      • 2011-05-21
      相关资源
      最近更新 更多