【问题标题】:Where do I reload a tableView from the choice of a UIAlertController?我在哪里从 UIAlertController 的选择中重新加载 tableView?
【发布时间】:2020-04-24 08:36:44
【问题描述】:

我有一个UITableView 带有一些滑动操作。其中一个通过UIAlertController 显示操作表,并让用户更改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?的闭包有什么关系吗?

【问题讨论】:

    标签: swift xcode uikit


    【解决方案1】:

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

    您应该在UIAlertAction.init 接受的handler 闭包中调用reloadData。这是用户选择操作时将调用的闭包。这里,你传递的是handleChangeType的返回值,所以你应该写在这里:

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

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

    【讨论】:

    • 感谢您的回复,但它仍然没有重新加载我的表(视觉上,我看到代码被执行了。reloadData 是否应该重建整个视图?:( 是的,我知道我可以使用移动,但我正在动态构建这些部分,只创建那些在表中具有相应行的部分..
    • @perage 尝试在闭包中放置一个断点,reloadData 是否真的被调用了
    • 如果您可以显示更多代码也会有所帮助@perage 例如,self?.handleChangeType(item: item, type: type) 行中的item 来自哪里?你是如何实现表格视图数据源的?
    • 它被称为是。该项目来自let item = sections[indexPath.section][indexPath.row] 内部trailingSwipeActionsConfigurationForRowAt。当关闭 ViewController 并再次打开它时,所有内容都已按应有的方式重新加载 - 但是当我在闭包内调用它时它不会发生:(可能是 tableView 在闭包内不可用吗?我试图得到用if let index = self.tableView.indexPathForSelectedRow 刷了一行,但最终没有设置索引...
    • 调试,我看到我的部分结构仅在第一次加载时计算,下一个,它使用保存的属性。我怎样才能让它每次都计算而不使用保存的数组` var section: [SectionData] = { var section = [SectionData]() for type in orderItem.orderItemType.allValues { let items = Cart.sharedInstance.order.items .filter { $0.type == type } if !items.isEmpty { section.append(SectionData(type: type, data: items)) } } return section }()`
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 2017-08-01
    • 1970-01-01
    • 2011-06-12
    • 1970-01-01
    相关资源
    最近更新 更多