You need to enable JavaScript to run this app. Swift中如何使用SDWebImage在UITableView展示图片及解决cell同图问题
优惠活动
大模型
产品
解决方案
定价
更多

Swift中如何使用SDWebImage在UITableView展示图片及解决cell同图问题

问题根源

所有UITableView单元格显示同一张图片,是两处逻辑错误叠加导致的:

  1. 配置单元格时,你没有按当前行的索引取对应商品的图片地址,反而从UserDefaults中读取同一个key存储的单值URL。
  2. 接口请求的循环里,你每次遍历到一个商品,就把当前商品的图片地址覆盖写入UserDefaults的同一个"url"key下,循环结束后UserDefaults里存的永远是接口返回的最后一个商品的图片地址,所有单元格读这个值自然会显示同一张图。

另外你本身已经在接口循环中把所有商品的图片地址存入了array_product_image数组,这个数组根本没有在单元格配置逻辑中被使用,属于冗余操作。

修正方案

1. 调整接口请求逻辑

删掉所有往UserDefaults写图片地址的冗余代码,同时在重新请求数据时清空所有旧的数据源数组,避免数据错位:

Alamofire.request("http://192.168.80.21:3204/api/product/get_all_products", headers: headers).responseJSON { [self] response in
    switch response.result {
    case .success:
        let myresponse = try? JSON(data: response.data!)
        let resultArray = myresponse
        
        // 清空所有旧数据源,避免复用残留旧数据
        self.array_product_name.removeAll()
        self.array_product_price.removeAll()
        self.array_product_description.removeAll()
        self.array_product_compamnyName.removeAll()
        self.array_product_image.removeAll()
        
        for i in resultArray!.arrayValue{
            let product_name = i["product_name"].stringValue
            self.array_product_name.append(product_name)
            
            let product_price = i["price"].stringValue
            self.array_product_price.append(product_price)
            
            let product_des = i["description"].stringValue
            self.array_product_description.append(product_des)
            
            let product_comName = i["company_name"].stringValue
            self.array_product_compamnyName.append(product_comName)
            
            let product_image  = i["image_url"].stringValue
            self.array_product_image.append(product_image)
        }
        
    case .failure(let error):
        print("接口请求失败: \(error.localizedDescription)")
    }
    self.tableView.reloadData()
}

2. 调整单元格配置逻辑

删掉读UserDefaults的逻辑,直接按当前单元格的索引从数据源数组中取对应的图片地址加载:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CellTableViewCell
    
    // 按行取对应的数据配置
    cell.productName.text = array_product_name[indexPath.row]
    cell.productPrice.text = array_product_price[indexPath.row]
    
    // 取当前行对应的图片地址,加空判断避免强制解包崩溃
    let imageUrlString = array_product_image[indexPath.row]
    if let imageUrl = URL(string: imageUrlString) {
        // 加载图片时可以搭配占位图,避免单元格复用时出现上一个cell的图片残留
        cell.productImageLbl.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "占位图"))
    } else {
        cell.productImageLbl.image = UIImage(named: "占位图")
    }
    
    return cell
}

额外注意点

  • 不要把临时接口返回的列表数据存入UserDefaults,它是用来存储需要持久化的轻量配置的,这类随页面展示变化的列表数据直接存在页面的成员变量数组里即可。
  • 加载网络图片时加上空值判断,避免异常URL触发强制解包导致应用崩溃。

内容的提问来源于stack exchange,提问作者Mahrez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.18 02:45:02