MVVM移动应用的最佳实践

时间:2022-02-21 16:00:57

I have serious doubts on how in deep we have to use view model.

我很怀疑我们到底要如何使用视图模型。

Let me explain with an example (in Swift, but language isn't important), simple view controller with a table view inside and a related view model.

让我用一个示例(在Swift中,但是语言并不重要)、一个包含表视图和相关视图模型的简单视图控制器来解释。

class FooViewController: UIViewController, UITableViewDelegate, UISearchBarDelegate {

     let viewModel = FooViewModel()

     @IBOutlet var tableView: UITableView!

     override func viewDidLoad() {
        super.viewDidLoad() 
        tableView.delegate = self
        tableView.dataSource = self
     }

    // MARK: - Table view delegates -

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return viewModel.heightForRow()
    }    
}

class FooViewModel {

    // MARK: - Table view management -

    func heightForRow() -> CGFloat {
        return 60.0
    }

}

Is a correct practice to delegate to the view model, for example, the height of each cell?
Generally, is ok delegate to view model UI "decision" on its aspect?

委托给视图模型(例如,每个单元格的高度)是正确的做法吗?一般来说,是否可以委托视图模型UI“决策”方面呢?

1 个解决方案

#1


1  

My general rule for placing things in the view model is if I will test them or not. Since we don't test view controllers, if something needs to be tested, consider placing it in the view model. If the row height is calculated, I'd consider placing it in the view model so it can be tested.

在视图模型中放置东西的一般规则是我是否要测试它们。由于我们不测试视图控制器,所以如果需要测试某些东西,请考虑将其放在视图模型中。如果计算行高度,我将考虑将它放在视图模型中,以便进行测试。

#1


1  

My general rule for placing things in the view model is if I will test them or not. Since we don't test view controllers, if something needs to be tested, consider placing it in the view model. If the row height is calculated, I'd consider placing it in the view model so it can be tested.

在视图模型中放置东西的一般规则是我是否要测试它们。由于我们不测试视图控制器,所以如果需要测试某些东西,请考虑将其放在视图模型中。如果计算行高度,我将考虑将它放在视图模型中,以便进行测试。