我有一个 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/