我有一个显示图像或文本的 UITableViewCell。我已将我的 UIImageView 高度和宽度设置为 <= 150,以便在图像不存在但文本存在的情况下它不会影响单元格高度。 (这是一个消息传递应用程序)
现在我的问题是,单元格在加载后不显示图像,用户需要返回并再次查看此屏幕才能看到图像。我该如何解决?
加载图像之前:
图片加载成功后:
如你所见,它没有显示,只有 View 被展开了
如果用户按下 BACK 并再次出现在该 View 中,
图像现在显示。
我该如何解决这个问题?因为我无法在 tableviewcell 中编写 tableview.reloaddata()
。
在我的 tableviewcell 中配置我的单元格的代码:
func configCell(message: Message) {
self.message = message
if message.fromId == currentUser {
sentView.isHidden = false
sentMsgLabel.text = message.textMessages
receivedMsgLabel.text = ""
receivedView.isHidden = true
timeReceived.text = ""
timeSent.text = message.timestamp
youLabel.text = "You"
themLabel.text = ""
if let ImageUrl = message.imageUrlLink {
self.receivedimg.loadImageUsingCacheWithUrlString(ImageUrl)
}
}
else {
sentView.isHidden = true
sentMsgLabel.text = ""
receivedMsgLabel.text = message.textMessages
receivedMsgLabel.isHidden = false
timeReceived.text = message.timestamp
timeSent.text = ""
// setting name for receipient
Database.database().reference().child("users").child(message.fromId!).child("name").observe(.value) { (datasnapshot) in
if let name = datasnapshot.value as? String {
self.themLabel.text = name
}
}
youLabel.text = ""
}
}
我的 loadImageUsingCacheWithUrlString 代码将是如下扩展:
let imageCache = NSCache<AnyObject, AnyObject>()
extension UIImageView {
func loadImageUsingCacheWithUrlString(_ urlString: String) {
self.image = nil
//check cache for image first
if let cachedImage = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
self.image = cachedImage
return
}
//otherwise fire off a new download
let url = URL(string: urlString)
URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
//download hit an error so lets return out
if error != nil {
print(error ?? "")
return
}
DispatchQueue.main.async(execute: {
if let downloadedImage = UIImage(data: data!) {
imageCache.setObject(downloadedImage, forKey: urlString as AnyObject)
self.image = downloadedImage
}
})
}).resume()
}
}
最佳答案
您的问题在下载图像后很明显,您的单元格没有及时更新,请在您的单元格中尝试 self.setNeedDisplays()。它告诉您的单元格应该在下一个 View 周期更新。
我建议使用 KingFisher 框架,而不是自己加载和捕获图像,它几乎可以完成我们处理来自远程服务器的图像所需的一切:下载、捕获、预取......并下载后立即显示图像强>
关于ios - 从 Firebase Swift 加载后单元格不显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50521170/