You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UITableView Cell无法显示图片问题求助(附代码)

问题分析与修复方案

核心问题1:TableView 数据源方法逻辑错误

你当前的numberOfSections(in:)返回imagesArray.count,这会让TableView创建与数组元素数量相同的分组,但每个分组默认行数为0,导致cellForRowAt方法根本不会被正确调用。正确逻辑应该是:

  • 仅创建1个分组
  • 分组内的行数等于数组元素数量

修改后的数据源方法:

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1 // 固定返回1个分组
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return imagesArray.count // 分组行数等于数组长度
}

核心问题2:图片写入错误被静默忽略

你用try? jpegdata.write(to: imagePath)屏蔽了所有写入异常,可能图片根本没成功保存到沙盒,导致后续读取时UIImage(contentsOfFile:)返回nil。建议替换为do-catch捕获错误,便于调试:

if let jpegdata = image.jpegData(compressionQuality: 0.8) {
    do {
        try jpegdata.write(to: imagePath)
    } catch {
        print("图片保存失败:\(error.localizedDescription)")
    }
}

其他疑问解答

  • 默认Cell是否自带imageView?
    系统默认的UITableViewCell(Basic/Subtitle等样式)自带imageView,只要你在Storyboard/XIB中使用的是系统预设样式,就无需额外添加。
  • App启动时imagesArray.count为0是否正常?
    这是预期行为,启动时数组还未添加任何元素,和cellForRowAt方法无关。只有当你添加图片后数组有内容,TableView才会加载Cell。

修复后的关键代码片段

override func viewDidLoad() {
    super.viewDidLoad()
    navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addPeople))
}

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return imagesArray.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Detail", for: indexPath)
    let person = imagesArray[indexPath.row]
    let imagePath = getDocumentsDirectory().appendingPathComponent(person.photos)
    cell.imageView?.image = UIImage(contentsOfFile: imagePath.path)
    cell.textLabel?.text = person.names
    return cell
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    guard let image = info[.editedImage] as? UIImage else { return }
    let imageName = UUID().uuidString
    let imagePath = getDocumentsDirectory().appendingPathComponent(imageName)
    
    if let jpegdata = image.jpegData(compressionQuality: 0.8) {
        do {
            try jpegdata.write(to: imagePath)
        } catch {
            print("图片保存失败:\(error.localizedDescription)")
        }
    }
    
    let person = Person(names: "Unknown", photos: imageName)
    imagesArray.append(person)
    tableView.reloadData()
    dismiss(animated: true)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 19:41:05