首页 > 解决方案 > 在 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

标签: iosswiftxcodeuitableviewuiimage

解决方案


添加 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")!

推荐阅读