[英]asynchronously loading images in swift
我有一張我想在表格視圖單元格的視圖頂部顯示的圖像。
我有以下代碼異步加載該圖像並將其添加到單元格:
if let image = value?["image"] {
let bookImageUrl = URL(string: image as! String)
let data = try? Data(contentsOf: bookImageUrl!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch
DispatchQueue.main.async {
if data != nil {
let imageView = UIImageView(image: UIImage(data: data!));
imageView.frame = CGRect(x: 0,
y: 95,
width: cell.frame.size.width,
height: 150)
imageView.contentMode = .scaleAspectFill
imageView.isUserInteractionEnabled = false
cell.addSubview(imageView)
let label = UILabel(frame: CGRect(x: 10,
y: cell.frame.size.height-60,
width: cell.frame.size.width,
height: 50));
label.textColor = UIColor.black
label.backgroundColor = UIColor.init(red: 1, green: 1, blue: 1, alpha: 0.5)
label.font = UIFont(name: "CeraPro-Bold", size: 16)
label.text = " \(title)"
cell.addSubview(label)
}
}
}
不幸的是,有時圖像無法加載。 難道我做錯了什么?
如果你在func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
中使用 tableView.dequeueReusableCell ( tableView.dequeueReusableCell(withIdentifier: "cellIdentifier", for: indexPath)
因此,與您提到的問題一樣,有時圖像不會顯示,這可能是因為UITableView
正在重用單元格,因此,如果您對每個if
語句都使用else
會更好。 或者,您可以使用SDWebImage或Kingfisher之類的東西進行圖像緩存。
另請注意,由於UITableView
確實重用了每個單元格,因此最好刪除所有子視圖或在 class 中為“UITableViewCell”創建一個變量,然后以編程方式添加任何視圖,如代碼cell.addSubview(imageView)
和cell.addSubview(label)
the imageView
and label
is getting initialized and added over and over for every reuse and every URL check, Here what you can do is create a variable for label
and imageview
in the cell and initialize only if the variable is nil
and assign之后的圖像。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.