Swift TableView从Firebase Storage加载头像错位问题求助
聊天页UITableViewCell头像错位问题排查与修复
错位产生的核心原因
这类问题完全是UITableView复用机制和异步图片加载的逻辑冲突导致的:
- UITableView滚动过程中,不可见的cell会被系统回收,重新分配给其他位置的indexPath使用
- 从Firebase Storage拉取头像是异步耗时操作,当图片加载完成的回调触发时,之前发起请求时绑定的cell可能已经被复用,分配给了其他用户的消息
- 原代码在网络回调中直接给捕获到的cell引用赋值,没有校验当前cell对应的身份,就会出现旧请求的图片覆盖新内容的错位
- 你观察到的“返回上级页面再进来就正常”的现象,本质是重新进入页面时所有cell都是全新初始化的,没有复用流程,异步请求回调对应的都是初始绑定的cell,所以不会出现错位
- 你之前重写
prepareForReuse做了界面重置,但没有绑定身份校验逻辑,无法拦截已经发出去的网络请求回调,所以没有解决问题
具体修复步骤
1. 给自定义Cell增加身份标记
在CustomMessageCell中新增属性,记录当前cell绑定的用户ID,作为后续回调校验的依据,同时在复用清理逻辑中重置该标记:
import UIKit class CustomMessageCell: UITableViewCell { // 新增:记录当前cell绑定的用户ID var currentBoundUid: String? @IBOutlet weak var messageBody: UILabel! @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var messageBubble : UIView! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var messageBodyTextView: UITextView! @IBOutlet weak var userPicture: UIImageView! @IBOutlet weak var imageButton: UIButton! override func prepareForReuse() { super.prepareForReuse() // 原有界面重置逻辑保留 userPicture.image = nil messageBodyTextView.text = "" usernameLabel.text = "" timeLabel.text = "" // 新增:清空绑定的用户ID,标记cell已进入可复用状态 currentBoundUid = nil } }
2. 重构图片加载逻辑,增加回调身份校验
修改cellForRowAt中的头像加载流程,核心逻辑是:
- 发起网络请求前,给cell绑定当前消息对应的用户ID
- 捕获这次请求对应的目标用户ID,而不是直接捕获cell引用
- 网络回调触发时,先校验:如果cell已经被复用、绑定了其他用户ID,就直接丢弃这次回调结果,不做任何赋值操作
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let message = messageArray[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "customMessageCell", for: indexPath) as! CustomMessageCell // 原有基础配置保留 cell.selectionStyle = .none cell.messageBodyTextView.text = message.messageBody cell.usernameLabel.text = message.name cell.timeLabel.text = dateToShow cell.userPicture.layer.cornerRadius = cell.userPicture.frame.height / 2 cell.userPicture.clipsToBounds = true cell.userPicture.image = nil // 给cell绑定当前消息对应的用户ID cell.currentBoundUid = message.uid // 捕获本次请求关联的目标UID,避免循环引用 let targetUid = message.uid let imagePath = self.storageRef.reference(withPath: "\(targetUid)/resizes/profilImage_150x150.jpg") // 弱引用捕获cell,避免循环持有 imagePath.getData(maxSize: 10 * 1024 * 1024) { [weak cell] (data, error) in // 校验cell是否还存在 guard let cell = cell else { return } // 核心校验:只有cell绑定的UID和本次请求的目标UID一致,才执行赋值 guard cell.currentBoundUid == targetUid else { return } if let error = error { cell.userPicture.image = UIImage(named: "emptyProfilPic") print("Got an error fetching data : \(error.localizedDescription)") return } if let data = data, let image = UIImage(data: data) { cell.userPicture.image = image } } return cell }
3. 性能优化(可选)
增加一层内存头像缓存,把已经加载过的头像按用户ID存储,避免重复发起网络请求,同时进一步降低错位概率:
- 在
ConversationViewController中新增缓存属性:
private let avatarCache = NSCache<NSString, UIImage>()
- 加载头像前先查缓存,命中缓存就直接设置,未命中再发起网络请求,请求成功后把图片存入缓存。
内容的提问来源于stack exchange,提问作者olivierm
相关产品推荐
相关产品推荐

