表格视图中的图像会自动重新加载

时间:2018-06-08 10:41:49

标签: swift uitableview

我有一个带有一些viewControllers的TabBarController。在一个,我有一个UITableview与一些图像,但当我插入一个新的图像并返回到饲料部分,我看到新的图像,但当我滚动各种图像,图像自动重新加载;它们不会保持固定状态,但在我跑步时会充电。溶液

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexPath) as! PostCell
    cell.postID = self.posts[indexPath.row].postID
    cell.userImage.layer.cornerRadius = 25.0
    cell.userImage.clipsToBounds = true
    cell.author.text = self.posts[indexPath.row].nameuser
    cell.userImage.downloadImage(from: self.posts[indexPath.row].userimage)
    cell.postImage.downloadImage(from: self.posts[indexPath.row].pathToImage)
    cell.caption.text = self.posts[indexPath.row].caption

    return cell
}

func loadPosts() {
    followpeople()
    Database.database().reference().child("posts").observe(.childAdded) { (snapshot: DataSnapshot) in
        if let dict = snapshot.value as? [String: Any] {
            let captionText = dict["caption"] as! String
            let photoUrlString = dict["photoUrl"] as! String
            let photoimage = dict["profileImageUrl"] as! String
            let author = dict["Author"] as! String
            let postid = dict["postID"] as! String
            let uda = dict["uid"] as! String
            let like = dict["likes"] as! Int
            let date = dict["date"] as! String
            let posst = Post()
            posst.nameuser = author
            posst.likes = like
            posst.caption = captionText
            posst.postID = postid
            posst.pathToImage = photoUrlString
            posst.userimage = photoimage
            posst.userID = uda
            self.posts.append(posst)
            self.tableView.reloadData()

        }
    }
}

func downloadImage(from imgURL: String!) {
    let url = URLRequest(url: URL(string: imgURL)!)
    let task = URLSession.shared.dataTask(with: url) {
        (data, response, error) in
        if (error != nil) {
            print(error!)
            return
        }
        DispatchQueue.main.async {
            self.image = UIImage(data: data!)
        }
    }
    task.resume()
}

1 个答案:

答案 0 :(得分:1)

因为这两行问题

cell.userImage.downloadImage(from: self.posts[indexPath.row].userimage)
cell.postImage.downloadImage(from: self.posts[indexPath.row].pathToImage)

他们会再次获取图片,即使他们刚刚下载时你还是会考虑使用SDWebImage来代替首次下载后缓存图片

1-通过为其添加pod来安装SDWebImage

2-用

替换2行
cell.userImage.sd_setImage(with: URL(string: self.posts[indexPath.row].userimage), placeholderImage: UIImage(named: "placeholder.png"))
cell.postImage.sd_setImage(with: URL(string: self.posts[indexPath.row].pathToImage), placeholderImage: UIImage(named: "placeholder.png"))