问题描述
在 StoreViewController 中,当单击按钮时,会打开一个名为 AddStoreVC 的 ModalViewController。
然后在 AddStoreVC,当我按下 Save 时,我想关闭它自己(我可以)并且当 StoreViewController 被加载时,tableView 将被刷新。
viewWillAppear、viewDidAppear 或之前线程中的任何替代方案都不适用。
感谢您的支持。
解决方法
您可以使用闭包、委托或通知(甚至 KVO 也是一种解决方案)。既然你有一对一的关系,我会选择闭包或模式。
关闭:
添加将模态呈现的 ViewController (AddStoreVC)
var onWillDismiss: (() -> Void)?
当你调用 dismiss(animated:completion:)
时,调用 onWillDismiss?()
在呈现的 ViewController 中,获取对模态控制器的引用,然后执行:
modalVC.onWillDismiss = { [weak self] in
self?.myTableView.reloadData()
}
我没有传递参数 (()
),但如果您还想检索参数,请添加它。想象一下你想要一个 Int:
var onWillDismiss: ((Int) -> Void)?
onWillDismiss?(theIntIWantToPass)
modalVC.onWillDismiss = { [weak self] theIntPassed in
print(theIntPassed)
self?.myTableView.reloadData()
}
代表:
你也可以使用委托模式:
创建委托:
protocol AddStoreVCCustomProtocol {
func modalVCWillDismiss(_ modalVC: AddStoreVC)
func modalVC(_ modalVC,willDimissWithParam param: Int)
}
使演示者符合它:
extension StoreViewController: AddStoreVCCustomProtocol {
func modalVCWillDismiss(_ modalVC: AddStoreVC) {
myTableView.reloadData()
}
func modalVC(_ modalVC,willDimissWithParam param: Int) {
print("theIntPassed with delegate: \(param)")
myTableView.reloadData()
}
}
向 Modal 添加一个属性以拥有一个委托:
weak var customDelegate: AddStoreVCCustomProtocol?
并在 dismiss(animated:completion:)
: customDelegate?.modalVCWillDismiss(self)
或 `customDelegate?.modalVC(self,willDimissWithParam: theIntIWantToPass) 上调用它