首页 > 解决方案 > 单元格突出显示默认图像而不是实际图像

问题描述

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

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()
        
    } 
    //...
}

标签: iosswiftuitableview

解决方案


如果您仅在正确显示图像时遇到问题,我建议您highlightedImage使用UIImageView.

UITableViewCell具有.highlighted 属性(当单元格被按下时)。因此,如果单元格包含UIImageView内部,那么当您选择/突出显示单元格时,UIImageView将使用.highlightedImage代替 just .image

因此,作为对问题的备份和修复,您还可以提供/告诉UIImageView 显示头像,即使它被突出显示。


推荐阅读