ios - 在 Table View UIImage 中使用 SD_setImage 缓存
问题描述
我想在我的表视图中为 UIImage 使用 sd_setImage。但我不确定如何...
func feedsImage() {
Database.database().reference(withPath: "Users/\(self.userID)/Images").observe(.childAdded, with: { (snapshot: DataSnapshot) in
if let userDict = snapshot.value as? [String:Any] {
let getphotoUrl = userDict["photoUrl"] as! String
let post = Post(getphotoUrl: getphotoUrl)
self.post.append(post)
print(self.post)
self.myTableView.reloadData()
}
})
}
这是表格视图
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .default, reuseIdentifier: "myCell")
DispatchQueue.global().async {
let postImage = self.post[indexPath.row]
if let photoUrl = URL(string: postImage.photoUrl!) {
do {
let data = try Data(contentsOf: photoUrl)
DispatchQueue.main.async {
cell.imageView?.image = UIImage(data: data)
cell.imageView?.frame = CGRect(x: 0, y: 0, width: 450, height: 450)
} // DispatchQueue.main
} catch {
print("Error in re-sampling UIImage")
}
}
} // DispatchQueue.global
return cell
} //MARK:- cellForRowsAt
解决方案
添加 pod 并安装后,导入
import SDWebImage
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "myCell")
cell.imageView.sd_setImage(with: URL(string:post[indexPath.row].getphotoUrl), placeholderImage: UIImage(named: "placeholder.png"))
return cell
}
顺便说一句,更换这条线总是更好
let cell = UITableViewCell(style: .default, reuseIdentifier: "myCell")
和
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell")!
推荐阅读
- javascript - 显示/隐藏单选按钮,基于其他单选按钮
- c# - 如何使用 ICommand 停用 Xamarin 中的按钮
- javascript - 反应选择设置错误的值
- oracle - 无法在 Oracle NET 配置助手中配置侦听器
- ios - 在本地保存敏感数据的安全方法?
- javascript - 在 PriorityERP 上使用 :FORM_APP_NAME 变量
- reactjs - 使用 ref 更改组件背景 - 反应原生
- string - 在 XSLT 中拆分 url 字符串
- android - UsageStatsManager 没有为时间间隔提供适当的数据
- c# - 让 TcpClient 等到数据写入