我有一个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!)实际上会正确打印用户名,但是它们似乎无法正确传递到单元格中。

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

最佳答案

您不需要以下行:

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
}

07-28 03:54
查看更多