我与数百人进行了群聊,当我快速滚动时,有时用户图像会从某处跳转到其他位置,或者会为用户显示不正确的图像。
我已经关注了其他一些 SO 帖子,但我似乎仍然做错了一些事情。这里有什么突出的,我可以做些什么来解决这个问题?
谢谢!
final class MessageCell: UITableViewCell {
private lazy var profileImageView: UIImageView = {
let imageView = UIImageView()
imageView.layer.cornerRadius = 20
imageView.clipsToBounds = true
return imageView
}()
// MARK: – Init
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .none
addSubview(profileImageView)
setupConstraints()
}
private func setupConstraints() {
constrain(profileImageView) {
let size: CGFloat = 36
$0.width == size
$0.height == size
$0.bottom == $0.superview!.bottom - CGFloat(3)
$0.left == $0.superview!.left + CGFloat(12)
}
}
func configure(with presentable: CellPresentable) {
self.presentable = presentable
if let sender = presentable.sender, presentable.isFirstMessage {
profileImageView.setImage(url: (sender.object(forKey: "picture") as? PFFile)?.url, fallbackText: presentable.username)
} else {
PFUser.query()?.whereKey("objectId", equalTo: presentable.message.senderUserId).getFirstObjectInBackground { [weak self] user, error in
self?.profileImageView.setImage(url: (user?.object(forKey: "picture") as? PFFile)?.url, fallbackText: presentable.username)
}
}
}
// MARK: Reuse -
override func prepareForReuse() {
super.prepareForReuse()
profileImageView.kf.cancelDownloadTask()
profileImageView.image = nil
}
}
在我的视图控制器中:
let cell = tableView.dequeueReusableCell(withIdentifier: "MessageCell") as! MessageCell
let presentable = CellPresentable(for: message, isFirstMessage: isFirstMessage, isLastMessage: isLastMessage)
cell.configure(with: presentable)
return cell