首页 > 解决方案 > 我在哪里从 UIAlertController 的选择中重新加载 tableView?

问题描述

我有UITableView一些滑动动作。其中一个通过 显示操作表UIAlertController,并让用户更改 a 的类别UITableViewCell,使单元格出现在另一个部分中。

我试图实现的是在做出选择后重新加载 tableView,但似乎警报是异步调用的。有人可以帮我理解调用堆栈以及tableview.reloadData()调用的位置吗?

        let switchTypeAction = UIContextualAction(style: .normal, title: nil) { [weak self] (_,_,success) in

            let ac = UIAlertController(title: "Change type", message: nil, preferredStyle: .actionSheet)
            for type in orderItem.orderItemType.allValues where type != item.type {
                ac.addAction(UIAlertAction(title: "\(type.prettyName)", style: .default, handler: self?.handleChangeType(item: item, type: type)))
            }
            ac.addAction(UIAlertAction(title: "Cancel", style: .cancel))
            self?.present(ac, animated: true)
            tableview.reloadData()
            success(true)
        }

    func handleChangeType(item: orderItem, type: orderItem.orderItemType) -> (_ alertAction:UIAlertAction) -> (){
        return { alertAction in
            item.type = type
        }
    }

我会假设调用是按这个顺序执行的,但是在调试时我看到它self?.present(ac, animated: true)实际上是在块之后执行的,所以首先执行重新加载和成功响应。这与关闭有什么关系吗@escaping?

标签: swiftxcodeuikit

解决方案


是的,UIAlertController是“异步”的,因为呈现警报的 VC 在呈现警报时仍将运行代码。事实上,对于任何展示另一个 VC 的 VC,这通常都是正确的。

您应该调用接受reloadDatahandler闭包UIAlertAction.init。这是用户选择操作时将调用的闭包。在这里,您正在传递 的返回值handleChangeType,因此您应该将其写在这里:

func handleChangeType(item: orderItem, type: orderItem.orderItemType) -> (_ alertAction:UIAlertAction) -> (){
    return { alertAction in
        item.type = type
        self.tableView.reloadData()
    }
}

如果您知道移动项目的索引路径,则可以moveTow(at:to:)改为仅重新加载这两行,而不是使用所有内容


推荐阅读