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

如何在alertController关闭后自动更新tableView的展示内容

问题根因

  1. 你当前把statisticsTableView.reloadData()写在了present(alertController, ...)的同级位置,这行代码会在弹出alert的同时立刻执行,此时用户还没有点击alert的「添加」按钮,新数据还没写入Realm,所以刷新是无效的。
  2. 点击「添加」按钮写入新数据后,没有重新读取Realm的最新数据到你的data数据源数组,也没有在这个节点触发tableView刷新。
  3. 额外小问题:你的「添加」按钮误用了.cancel样式,系统会自动把它放到alert最左侧,不符合常规交互逻辑。

修复方案

直接调整addPlane方法的代码,把刷新逻辑移到「添加」按钮的点击回调内,同时更新数据源:

@IBAction func addPlane(_ sender: Any) {
    let alertController = UIAlertController(title: "На каком самолёте вы летали?", message: nil, preferredStyle: .alert)
    alertController.addTextField { (textfield) in }
    let alertCancel = UIAlertAction(title: "Отменить", style: .destructive) { (alert) in }
    // 修改添加按钮样式为default,新增weak self避免循环引用
    let alertAction = UIAlertAction(title: "Добавить", style: .default) { [weak self] alert in
        guard let self = self else { return }
        let newItem = alertController.textFields?.first?.text
        // 写入新数据到Realm
        RealmModel.shared.fillTableview(company: "Другие", plane: newItem ?? "", status: true)
        // 重新读取最新数据更新本地数据源
        self.data = RealmModel.shared.getSections()
        // 确保在主线程刷新UI
        DispatchQueue.main.async {
            self.statisticsTableView.reloadData()
        }
    }

    alertController.addAction(alertAction)
    alertController.addAction(alertCancel)
    present(alertController, animated: true, completion: nil)
    // 删掉原来写在这里的reloadData代码
}

可选优化

  • 你可以直接用Realm的Results类型作为tableView数据源,监听Results的变化通知,当数据发生变更时自动触发UI刷新,不需要每次手动调用getSections()拉取数据,性能更好也更省心。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 13:15:07