使用选择器时如何处理回调?
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()
}
}
在某处,您需要在您的视图模型中定义委托:
weak var viewDelegate: ViewDelegate
以及在创建 类 时分配它:
let model = ViewModel()
let view = ViewController()
model.viewDelegate = view
Swift官方文档有很多关于协议的内容:https://docs.swift.org/swift-book/LanguageGuide/Protocols.html
我将我的逻辑代码放在 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()
}
}
在某处,您需要在您的视图模型中定义委托:
weak var viewDelegate: ViewDelegate
以及在创建 类 时分配它:
let model = ViewModel()
let view = ViewController()
model.viewDelegate = view
Swift官方文档有很多关于协议的内容:https://docs.swift.org/swift-book/LanguageGuide/Protocols.html