我有一个 UITableViewController
,它是一个 ViewModel 类。我正在尝试使用 MVVM 模式构建我的应用程序。
我的 tableView 有一个显示图像的单元格,该图像有一个手势识别器,可以在按下时调用 View 模型中的方法。
此时,我想以模态方式呈现一个 ViewController
,其中包含一些嵌入的内容。
但是我的 TableView cell
符合 UITableViewCell
所以我无法从这里调用present。
我的 ViewModel 不符合任何要求,因此我也无法从那里调用 Present。
如何从 UITableViewCell
中触发模式显示?
最佳答案
您有几个选择,但我将介绍委托(delegate)解决方案。
这个想法是在MyViewModel
中定义协议(protocol)
和该协议(protocol)的属性,并使MyViewController
符合它。
下面是 MyViewModel
的样子:
protocol MyViewModelDelegate: class {
func didTapOnCell()
}
class MyViewModel {
// Please note the delegate is weak and optional
weak var delegate: MyViewModelDelegate?
// This function handle gesture recognizer taps
@objc func handleImageViewTap() {
delegate?.didTapOnCell()
}
// Here is the rest of the ViewModel class...
}
然后在 MyViewController
中,将 viewModel 的委托(delegate)属性设置为 self
并符合协议(protocol)函数(我假设 View Controller 引用 View 模型实例)。
class MyViewController: UITableViewController {
func setup() {
// ...
// When MyViewModel is initialised, set the delegate property to self
myViewModel.delegate = self
}
}
extension MyViewController: ViewModelDelegate {
func didTapOnCell() {
// ...
// Allocate instance of anotherViewController here and present it
self.present(anotherViewController, animated: true, completion: .none)
}
}
通过这种方式,您可以让 MyViewController
了解 MyViewModel
中发生的事情并采取相应的行动。
请注意,有必要将 delegate
属性设为可选,以避免循环保留。
关于ios - 从 UITableViewController 的 View 模型呈现模态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53668613/