iOS MVVM 处理初始视图状态

iOS MVVM handling initial view state

我正在尝试在 Objective C 中使用没有 Rx 的 MVVM,基本上类似于 MVP。我有一些非常基本的疑惑,我想澄清一下

1.) 如何根据配置在视图中加载初始视图状态。即当 UI 组件的初始状态可以根据某些配置值更改时。对于前。根据全局配置,视图中的按钮最初可以是 enabled/disabled/hidden。在视图中可以有很多 UI 组件的情况下,应如何呈现初始视图状态?

2.) 如何处理单个 UI 组件的状态?

3.) 我很困惑谁应该触发某些操作,例如,让我们说 "validation"。例如,在登录屏幕中,谁应该触发 email/password 值的验证?

哇,这个里面有很多问题......让我们看看我能梳理出什么:

How this initial view state should be rendered where there can be lots of UI components in a view?

当不使用响应式系统时,无论是 Objective-C 还是 Swift,我的视图控制器以 configureWithViewModel: (Obj-C) 或 configure(viewModel:) ( swift) 在 viewDidLoad 中以及每次视图模型更改时调用的函数。当调用configure方法时,初始状态在viewDidLoad中呈现。

Should view model pass this config (or view state object) to view and view decides how to renders itself? Should View model pass the state of each UI element to the view?

视图决定如何 呈现自身,viewModel 决定什么 值应该是什么。 viewModel 只处理视图中的动态部分。因此,例如,如果 UILabel 中唯一不同的是文本,那么 viewModel 会为文本提供一个字符串。如果 UILabel 还更改了 textColor,则 viewModel 会同时提供 String 和 UIColor。

In case of Rx should VM have one view state property or state properties of each UI component?

就我个人而言,我为 viewModel 为每个动态视图提供了一个单独的 Observable,但是在非 Rx 上下文中我觉得这太复杂了并且只有一个 update 可以同时提供所有状态.

How to handle states of individual UI components?

  • Should VM ever ask the view to update its view state via methods like enableButton1, hideTextView etc. or
  • It should just pass the "events" or data to the view and let the view decide how to react to these events.

通过数据。观点并没有决定性。例如 UIButton 有一个 isEnabled 属性。本例中的数据显然是一个Bool。 viewModel 提供 Bool 并且 ViewController 只是将该 bool 分配给 View(或者视图将其分配给自己。)

In Rx world should view bind with individual state properties or to just event properties?

状态属性。类似于:

viewModel.isMyButtonEabled
    .bind(to: myButton.rx.isEnabled)

I am confused who should trigger certain operations, for instance, let's say "validation". For example in a login screen who should trigger the validation of email/password values?

上面的措辞有点混乱。没有 "triggers operations"。当输入内容时,视图的输入部分会通知视图模型,而视图模型要么忽略该输入,要么更新其状态。如果它更新了它的状态,那么它将更新发送到视图的输出部分。因此,以验证为例,您可以执行以下两项操作之一:

  • 当用户点击 "send" 按钮时,视图模型将收到电子邮件和密码。它负责根据这些字符串的值做什么并更改其状态。然后它通知视图控制器它的状态已经改变。

  • 当用户在每个文本字段中输入数据时,甚至可能针对每个单独的字符,视图模型都会收到当前文本字段值。它负责根据这些字符串的值做什么并更改其状态。然后它通知视图控制器它的状态已经改变。

  • Should view ask VM to validate and then ask to execute login process or
  • Should view just pass the click action to VM with email/password values and VM decides whether to do validation or not and what to do if it passes or fails?

后者。这个想法是将尽可能多的工作 移出 视图控制器,以便更容易 control/test.