swift - 可重用的 UICollectionViewCell 不更改 UIImageView 属性(显示重复项)

标签 swift uicollectionview

我有一个 UICollectionView,其中包含一个包含 UIImageView 的可重用单元格,但 Collection View 在 ImageView 中为集合中的每个单元格项目显示相同的图像。

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

    let path = indexPath.item
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "friendAvatar", for: indexPath) as! AvatarCollectionViewCell
    cell.avatarView.image = friends[path].userAvatar
    return cell

}


class AvatarCollectionViewCell: UICollectionViewCell {


    var avatarView = UIImageView()


    override init(frame: CGRect) {
        super.init(frame: frame)

        prepareForReuse()
        config()

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    override func prepareForReuse() {

        avatarView.image = nil
        avatarView.removeFromSuperview()

    }


    func config() {

        avatarView.frame = CGRect(x: 0, y: 0, width: 64, height: 64)
        avatarView.layer.cornerRadius = 64 / 4
        avatarView.clipsToBounds = true
        avatarView.contentMode = .scaleAspectFill
        addSubview(avatarView)

    }


}

最佳答案

首先,您在 prepareForReuse() 中将 ImageView 从其 super View 中移除,但您永远不会将其添加回来。 init() 不会在重用单元格时被调用,config() 也不会。除非有特殊原因,否则不需要从其父 View 中删除 ImageView 。只需将其图像设置为 nil 就足够了。

此外,设置断点并验证 friends[path].userAvatar 返回图像的有效路径。

关于swift - 可重用的 UICollectionViewCell 不更改 UIImageView 属性(显示重复项),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46965947/

相关文章:

json - 使用原生 swift 解析返回的 Json

ios - UICollectionView 错误 : cells must be retrieved by calling -: -dequeueReusableCellWithReuseIdentifier:forIndexPath:

ios - 如何在 swift 4 的 Collection View 中刷新数据?

ios - NSInternalInconsistencyException - “请求 MSCollectionElementKindCurrentTimeHorizo​​ntalGridline 装饰 View 的布局属性

ios - 旋转后的 CollectionView 布局

ios - 如何在重定向到/login后再次登录而不出现任何http错误

ios - 为什么我们在 fetchRequest() 声明之前放置 @nonobjc 属性?

swift - 结构内部协议(protocol)

ios - ld : framework not found after pod install

swift - 在 viewDidAppear 中快速淡入数据