How to implement a basic UITextField input + UIButton action scenario using ReactiveCocoa 3?

后端 未结 2 807
梦如初夏
梦如初夏 2021-02-04 16:32

I\'m a Swift and ReactiveCocoa noob at the same time. Using MVVM and Reactive Cocoa v3.0-beta.4 framework, I\'d like to implement this setup, to learn the basics of the new RAC

2条回答
  •  走了就别回头了
    2021-02-04 16:56

    From the ReactiveCocoa/CHANGELOG.md:

    An action must indicate the type of input it accepts, the type of output it produces, and what kinds of errors can occur (if any).

    So currently there is no way to define an Action without an input.

    I suppose you could declare that you don't care about input by making it AnyObject? and creating CocoaAction with convenience initialiser:

    cocoaAction = CocoaAction(viewModel.action)
    

    Additional remarks

    • I dont't like using AnyObject? instead of Bool for validatedTextProducer. I suppose you preferred it because binding to the buttonEnabled property requires AnyObject?. I would rather cast it there though, instead of sacrificing type clarity of my view model (see example below).

    • You might want to restrict execution of the Action on the view model level as well as UI, e.g.:

      class ViewModel {
      
          var text = MutableProperty("")
          let action: Action
      
          // if you want to provide outside access to the property
          var textValid: PropertyOf {
              return PropertyOf(_textValid)
          }
      
          private let _textValid = MutableProperty(false)
      
          init() {
              let validation: Signal -> Signal = map { string in
                  return count(string) > 3
              }
      
              _textValid <~ text.producer |> validation
      
              action = Action(enabledIf:_textValid) { _ in
                  //...
              }
          }
      }
      

      And binding to buttonEnabled:

      func bindSignals() {
          buttonEnabled <~ viewModel.action.enabled.producer |> map { $0 as AnyObject }
          //...
      }
      

提交回复
热议问题