TableViewCell ImageView始终显示不同的数据

时间:2018-12-30 12:45:35

标签: swift uitableview

我正在聊天,想显示用户个人资料图片。 一切都会正确显示,但不会显示用户的个人资料图片。 每当我重新加载视图时,都会得到其他图片。

我通过以下几行加载Profileimage:

func showProfilImage(uid: String, completion: @escaping (UIImage) -> Void) {
    UserApi.shared.observeUser(uid: uid) { (user) in
        guard let url = URL(string: user.profilImageUrl!) else { return }

        URLSession.shared.dataTask(with: url) { (data, response, error) in
            guard error == nil, let data = data, let image = UIImage(data: data) else { return }
                DispatchQueue.main.async {
                    let finishedImage = image.withRenderingMode(.alwaysOriginal)
                    completion(finishedImage)
                }
                }.resume()
    }
}

然后我用以下几行在showProfilImage中呼叫cellForRowAt

self.showProfilImage(uid: self.items[indexPath.row].user.uid!) { (image) in
    cell.profilePic.image = image
}

更新

现在,我实现了sdWebImage并使用URL完成:

func showProfilImage(uid: String, completion: @escaping (URL) -> Void) {
    UserApi.shared.observeUser(uid: uid) { (user) in
        guard let url = URL(string: user.profilImageUrl!) else { return }
        completion(url)
    }
}

我在这里给我的showProfilImage打电话:

self.showProfilImage(uid: self.items[indexPath.row].user.uid!) { (url) in
            cell.profilePic.image = nil
            cell.profilePic.sd_setImage(with: url, completed: { (_, _, _, _) in
            })
        }

3 个答案:

答案 0 :(得分:1)

您当前的代码有出队问题,没有套现问题,为此,您可以使用SDWebImage

// TOUCHES in empty space:

private func addGestureRecognizers(){
    let tapGestureRecogniser = UITapGestureRecognizer(target: self, action: #selector(handleTapEmptySpaceGesture))
    tapGestureRecogniser.delegate = self
    collectionView.addGestureRecognizer(tapGestureRecogniser)
}


@objc func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
    // only handle tapping empty space (i.e. not a cell)
    let point = gestureRecognizer.location(in: collectionView)
    let indexPath = collectionView.indexPathForItem(at: point)
    return indexPath == nil
}

也类似

cell.profilePic.sd_setImage(with: URL(string:urlStr), placeholderImage: UIImage(named: "placeholder.png"))

UserApi.shared.observeUser(uid: uid) { (user) in 中会说一次

答案 1 :(得分:0)

如果您要正确获取每个用户的图像 那么您的问题可能在于滚动和出队单元格 要解决UITableViewCell自定义类中的此类问题,请在每次出队时使用此函数清除UIImageView

override func prepareForReuse() {
        super.prepareForReuse()
        self.imageView.image = nil  //setting the image to nil  when get dequeued to reuse 
    }

详细了解此功能Here

答案 2 :(得分:-1)

UITableView重用其视图,这意味着当您一次加载图像并且单元格脱离屏幕时,UITableView会将单元格带回屏幕以显示不同的数据源,但是先前加载的图像仍将显示在UIImageView上 添加此行代码

#navbar-bg {
  position: fixed;
  width: 20%;
  float: left;
}

#navbar {
  display: flex;
  align-items: center;
}

#body {
  margin-top: 200px;
  float: right;
  width: 80%;
}