cellForItemAt indexPath 单元格下载数据的问题

issues with cellForItemAt indexPath cell downloading data

我有一个 UIColelctionView 单元格,它应该包含位于 firebase 数据库中的用户名。

首先,我使用以下方法引用了自定义单元格:

let f = FriendCell()

在 cellForItemAt indexPath 中,我定义了每个单元格并引用了数据所来自的数组。然后我引用特定单元格将从中获取数据的个人用户。

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: userResultCellId, for: indexPath) as! FriendCell

    let user = users[indexPath.row]

    f.nameLabel.text = user.name
    print(f.nameLabel.text!)

    return cell
}

当我 运行 这样做时,控制台 print(f.nameLabel.text!) 实际上正确地打印了用户名,但是它们似乎没有正确地传递到单元格中。

我相信正在发生的事情是在下载数据之前设置每个单元格并且名称标签返回 nil 因为那里没有值。但奇怪的是,当我打印值时 returns 名称正确。有什么建议吗?

你不需要这条线:

let f = FriendCell()

去掉那个。然后在你的 cellForItemAt 中,你需要设置 cell 的属性,而不是 f.

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: userResultCellId, for: indexPath) as! FriendCell

    let user = users[indexPath.row]
    cell.nameLabel.text = user.name

    return cell
}