ios - 在 tableView 中下载图像(_ :cellForRowAt:) causing cells non-stop flashing

标签 ios swift uitableview

我希望在方法 tableView(_:cellForRowAt:) 上为每个 UITableViewCell 延迟下载图像。当表格 View 显示在屏幕上时,它在每个单元格上不停地闪烁,我无法滚动 tableView。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MessageCell", for: indexPath) as! MessageCell
    let row = indexPath.row

    cell.content.delegate = self
    cell.content.text = messages[row].content
    cell.date.text = messages[row].createdDateStrInLocal
    cell.messageOwner.text = messages[row].user

    self.fetchUserAvatar(avatarName: messages[row].user, handler: ({ img in
        cell.profileImageView.image = img
        tableView.reloadRows(at: [indexPath], with: .automatic)
    }))
    return cell
}

fileprivate func fetchUserAvatar(avatarName: String, handler: @escaping (UIImage) -> Void){
    guard !avatarName.isEmpty, let user = self.user, !user.isEmpty else { return }
        let url = URL(string: self.url + "/userAvatarURL")
        var request = URLRequest(url: url!)
        let body = "username=" + user + "&avatarName=" + avatarName
        request.httpMethod = "POST"
        request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
        request.httpBody =  body.data(using: .utf8)
        defaultSession.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
            guard error == nil else {
                print(error!)
                return
            }
            if let httpResponse = response as? HTTPURLResponse, 200...299 ~= httpResponse.statusCode, let data = data, let urlStr = String(data: data, encoding: String.Encoding.utf8), urlStr != "NULL", urlStr.contains("http"), let url = URL(string: urlStr) {
                self.defaultSession.dataTask(with: url, completionHandler:{ data, respone, error in
                    guard error == nil else {
                        print(error!)
                        return
                    }
                    DispatchQueue.main.async {
                        if let httpResponse = response as? HTTPURLResponse, 200...299 ~= httpResponse.statusCode, let data = data, let img = UIImage(data: data) {
                            self.cacheImage.setObject(img, forKey: avatarName as NSString)
                            handler(img)
                        }
                    }
                }).resume()
            }
        }).resume()
}

最佳答案

尽管这不是将图像下载到单元格的安全方法,您需要删除 tableView.reloadRows(at: [indexPath], with: .automatic)。这导致无限循环。

并确保在更新图像时更新约束。

关于ios - 在 tableView 中下载图像(_ :cellForRowAt:) causing cells non-stop flashing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44047509/

相关文章:

ios - UISwipeGesture 'unrecognized selector sent to instance'

ios - 如何创建一个发出键盘高度的 RxSwift Observable?

ios - Cocos2d v3 在子节点上应用着色器

swift - 使新的 TableView 单元格 textField 成为第一个响应者

iphone - UITableView 滚动 UINavigationBar

swift - double 数组的划分

ios - 通过 UID 获取 Google 个人资料图片 url

ios - 如何将此数组拆分为单独的元素/数组以在 Swift 的表中使用?

ios - 具有两个不同自定义单元格的 UITableview 在滚动时重叠

ios - 如何在 tableView 之前添加 "Loading" View Controller