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

Swift/Xcode模拟器中TableView不显示白屏问题求助

TableView白屏问题的排查与修复方案

最核心问题:未触发数据加载

你的getData()方法仅定义但从未被调用,viewDidLoad中没有执行该方法,导致nameArray始终是空数组,numberOfRowsInSection返回0,TableView没有可显示的行,因此呈现白屏。

修复代码:在viewDidLoad末尾添加数据加载调用:

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.delegate = self
    tableView.dataSource = self
    navigationController?.navigationBar.topItem?.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addButtonClicked))
    // 新增:触发数据加载
    getData()
}

检查TableView的IBOutlet连接

如果Storyboard/XIB中的TableView未与代码里的@IBOutlet weak var tableView: UITableView!正确绑定,tableView会是nil,无法在界面上渲染。

排查方式:

  • 打开Storyboard,选中当前ViewController,在右侧Connections Inspector面板中,确认tableView已连线到界面上的TableView组件。
  • 或在viewDidLoad中添加打印语句验证:
print(tableView ?? "TableView未完成绑定")

优化数据加载与刷新逻辑

  1. 移出循环内的重复刷新:当前代码在遍历数据时每次添加元素都刷新TableView,会造成不必要的性能损耗,应在所有数据处理完成后统一刷新:
do{
    let results = try context.fetch(fetchRequest)
    // 清空旧数据,避免重复加载
    nameArray.removeAll()
    idArray.removeAll()
    for result in results as! [NSManagedObject] {
        if let name = result.value(forKey: "name") as? String{
            self.nameArray.append(name)
        }
        if let id = result.value(forKey: "id") as? UUID{
            self.idArray.append(id)
        }
    }
    // 循环结束后统一刷新TableView
    self.tableView.reloadData()
}catch{
    print("数据加载失败:\(error)")
}
  1. 添加数据清空操作:若多次调用getData(),旧数据会重复累积到数组中,因此每次加载前需清空数组。

CoreData实体属性匹配验证

确保CoreData模型中Paintings实体的属性类型与代码逻辑匹配:

  • name属性类型为String(可选/非可选需对应代码中的可选绑定逻辑)
  • id属性类型为UUID(或支持转换为UUID的类型)

若属性类型不匹配,value(forKey:)会返回nil,导致数组仍为空,TableView无内容可显示。

TableViewCell复用优化(可选)

当前代码直接创建UITableViewCell,推荐使用复用机制提升性能:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    var content = cell.defaultContentConfiguration()
    content.text = nameArray[indexPath.row]
    cell.contentConfiguration = content
    return cell
}

同时需在Storyboard中给TableViewCell设置Identifier为Cell。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 08:25:20