Ваш код неверен, потому что вы настраиваете свои ячейки один раз (в методе tableView:cellForRowAt:
), но когда вы прокручиваете представление таблицы, если пользователь чередуется, avatarImageView
, messageBackground
и ourMessageBackground
будут скрыты в конце концов.
Попробуйте обновить свой код так:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customMessageCell", for: indexPath)
cell.ourMessageBackground.backgroundColor = UIColor(displayP3Red: 59/255.0, green: 89/255.0, blue: 152/255.0, alpha: 1)
cell.ourMessageBody.textColor = UIColor.white
cell.avatarImageView.backgroundColor = UIColor(white: 0.95, alpha: 1)
cell.messageBackground.backgroundColor = UIColor(white: 0.95, alpha: 1)
self.tableView(tableView, willDisplay: cell, forRowAt: indexPath)
return cell
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let cell = cell as? CustomMessageCell else { return }
//Sets cell to message
let senderId = messageArray[indexPath.row].fromId
if senderId == Auth.auth().currentUser?.uid as String? {
//Messages We Sent
cell.ourMessageBody.text = messageArray[indexPath.row].messageBody
cell.avatarImageView.isHidden = true
cell.messageBackground.isHidden = true
cell.ourMessageBackground.isHidden = false
} else {
//Messages someone else sent
cell.messageBody.text = messageArray[indexPath.row].messageBody
cell.avatarImageView.isHidden = false
cell.messageBackground.isHidden = false
cell.ourMessageBackground.isHidden = true
//toId ProfileImage
if let imageID = toId {
let imagesStorageRef = Storage.storage().reference().child("profilepic/").child(imageID)
imagesStorageRef.getData(maxSize: 1*1024*1024, completion: { (data, error) in
if error != nil{
print(error)
return
}
DispatchQueue.main.async {
guard let c = tableView.cellForRow(at: indexPath) else { return }
c.avatarImageView?.image = UIImage(data: data!)
}
})
}
}
}
Кроме того, поскольку выборка аватара выполняется в фоновом режиме, при извлечении данных ячейка могла измениться. Таким образом, вы должны быть уверены, что ячейка все еще отображается. И вы должны кэшировать аватар, чтобы не получать его каждый раз.