kategoriManager.fetch(){kategoriItem, error in
DispatchQueue.main.async {
// Update UI
self.parentCategoryTableView.reloadData()
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (tableView == categoryDetailTableView) {
let kategoriDetailItem = selectedKategori[indexPath.row]
let kategoriDetailCell = tableView.dequeueReusableCell(
withIdentifier:"categoryDetailCell", for: indexPath) as! CategoryDetailCell
kategoriDetailCell.categoryDetailLabel.text = kategoriDetailItem.name
return kategoriDetailCell
}
let cell = tableView.dequeueReusableCell(
withIdentifier:"parentCategoryCell", for: indexPath) as! CategoryCell
let kategoriItem = kategoriManager.kategoriItem(at: indexPath.row)
cell.parentCategoryLabel.text = kategoriItem.name
cell.parentCategoryImageView.load(urlString: (base_img + kategoriItem.image!))
return cell
}
我有一个像上面这样的表格视图,但是当控制器加载表格视图时。仅显示 cell.parentCategoryLabel.text。直到我滚动表格视图后,图像才会加载。
class CustomImageView: UIImageView {
var imageURLString : String?
func load(urlString : String){
imageURLString = urlString
let url = NSURL(string: urlString)
image = nil
//imageCache exist,and use it directly
if let imageFromCache = imageCache.object(forKey: urlString as NSString) {
self.image = imageFromCache
return
}
DispatchQueue.global().async { [weak self] in
if let data = try? Data(contentsOf: url! as URL) {
DispatchQueue.main.async {
let imageToCache = UIImage(data: data)
if self?.imageURLString == urlString {
self?.image = imageToCache
}
imageCache.setObject(imageToCache!, forKey: urlString as NSString)
}
}
}
}
}
这是我的加载图像功能,我可以在不滚动的情况下加载tableView中的所有图像吗?我可以在没有像 sdWebImage 或 kingFisher 这样的库的情况下做到这一点吗?我更喜欢本机解决方案,因为我不想让应用程序变慢。
我从其他问题中找到了以下答案,已经解决了我的问题
https://stackoverflow.com/a/73840635/18088674
因此,在阅读该答案后,我在图像加载之前定义了宽度和高度,或者您可以在从 url 图像加载之前添加默认图像