单元格高亮显示默认图像而不是实际图像

Cell highlight shows default image instead of actual image

我在 table 的单元格中有头像图像。当我触摸一个单元格(突出显示)时,它会显示默认头像图像而不是实际图像。我不确定是什么原因造成的以及如何解决。有帮助吗?

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as? TableViewCell else {
        fatalError("Can't find cell")
    }
       
    //...
        
    cell.selectionStyle = .default
    self.configCell(cell: cell, indexPath: indexPath)

    //...
    
}

func configCell(cell: TableViewCell, indexPath: IndexPath) {
   
    //...

    // Avatar
    if let url = URL(string: urlString) {
        cell.avatarImageView.image = .defaultImage
        cell.tag = indexPath.row
        let task = URLSession.shared.dataTask(with: url) { data, response, error in
            guard let data = data, error == nil else { return }
            DispatchQueue.main.async {
                if cell.tag == indexPath.row {
                    cell.avatarImageView.image = UIImage(data: data)
                }
            }
        }
        task.resume()
        
    } 
    //...
}

如果您 无法正确显示图像,我建议您使用 highlightedImage 属性 或 UIImageView

UITableViewCell.highlighted 属性(当单元格被按下时)。因此,如果单元格内部包含 UIImageView,那么当您 select/highlight 单元格时, UIImageView 将使用 .highlightedImage 而不是仅 .image.

因此,作为备份和修复问题,您可以另外 provide/tell UIImageView 显示头像 即使突出显示。