[英]How do I handle callbacks when using selectors?
我将我的逻辑代码放在viewModel
中。 view
调用viewController
中的一种方法。 然后,该方法使用#selectors
viewModel
在需要使用tableView.reloadData()
重新加载tableView
之前,这可以正常工作。 那部分显然需要在view
中。
通常,这将通过使用多个闭包来完成。 但由于#selectors
不能有参数,我不能在最后一个调用的方法中有completion()
回调。 所以,我的问题是,我该如何解决这个问题? 使用#selectors
有什么好的选择吗? 我应该在view
中有一个观察者订阅viewModel
的最后一个方法吗? RxSwift 是替代品吗? 或者是否有使用#selectors
的解决方法?
RxSwift 是一个不错的选择,但如果你需要一些不那么繁重的东西,委托模式就是你所需要的:
protocol ViewDelegate {
// Other functions you might need
func reloadTableView()
}
Then in your viewController, you implement these:
class ViewController: ViewDelegate {
func reloadTableView() {
tableView.reloadData()
}
}
在某处,在您看来 model 您需要定义委托:
weak var viewDelegate: ViewDelegate
以及在创建类时分配它:
let model = ViewModel()
let view = ViewController()
model.viewDelegate = view
Swift official documentation has a lot more on protocols: https://docs.swift.org/swift-book/LanguageGuide/Protocols.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.