ios - 从 UITableViewController 的 View 模型呈现模态

标签 ios swift uitableview

我有一个 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/

相关文章:

iphone - 在 UITableView 之上覆盖 View

ios - 如何在 Swift 中将 SKScene 覆盖在 SCNScene 上?

ios - objective-C:为什么我的循环没有终止?

ios - 闭包内的 return 语句

关于 TableView 和构建自定义类模型的 iPhone MVC 问题

uitableview - iOS : How to let UITableView draw its cells out of its bounds?

ios - SKAction 跟随路径同时进行定向和旋转

ios - 如何在 xcode 中创建按钮数组?

ios - 如何向另一个类中的 UIButton 添加操作

ios - Swift 4 & iOS 12 : Using keyboard textContentType . 独立 View Controller 上的新密码