我用于消息传递UITableView
的{{1}}单元格仅在我向上或向下滚动表格视图时,有时在发送新消息时,才获得正确的高度尺寸。我已经看到大多数人使用ViewController
解决了这个问题,但是对我来说,它是行不通的。有什么想法吗?
automaticDimension和cell.layoutIfNeeded:
cell.layoutIfNeeded
设置单元的代码:
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
messageTableView.estimatedRowHeight = 120.0
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customMessageCell", for: indexPath) as! CustomMessageCell
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)
cell.layoutIfNeeded() //<-- Layout if needed
return cell
}
从Firebase检索消息的代码:
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
cell.layoutIfNeeded()
//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 }
cell.avatarImageView?.image = UIImage(data: data!)
}
})
}
}
}
答案 0 :(得分:0)
为什么都放
messageTableView.estimatedRowHeight = 120.0
return UITableView.automaticDimension
在您的tableView(_ tableView :, EstimateHeightForRowAt indexPath :)方法内?这样做是没有意义的,请使用EstimatedHeight来帮助tableView来创建您的单元格。结果,只需返回CGFloat就可以完成工作,即
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 120
}
为您的单元格添加AutomaticDimension。添加此内容:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}