How to bind rx_tap (UIButton) to ViewModel?

后端 未结 3 865
我在风中等你
我在风中等你 2021-02-05 15:52

I have authorization controller with 2 UITextField properties and 1 UIButton. I want to bind my View to ViewModel but don\'t know how to to do it. This is my AuthorizatioVC.swi

3条回答
  •  [愿得一人]
    2021-02-05 16:18

    First approach use PublishSubject

    class ViewController: UIViewController {
      @IBOutlet weak var loginBtn: UIButton!
      var vm: ViewModel?
      let disposebag = DisposeBag()
    
      override func viewDidLoad() {
          super.viewDidLoad()
          bindUi()
      }
    
      func bindUi() {
        (loginBtn.rx.tap).bind(to: vm!.loginSbj).addDisposableTo(disposebag)
      }
    }
    
    class ViewModel {
      let loginSbj = PublishSubject()
    
      init() {
        loginSbj.do(onNext: { _ in
          // do something
        })
      }
    
    }
    

    The second approach use Action

    class ViewController: UIViewController {
       @IBOutlet weak var loginBtn: UIButton!
       var vm: ViewModel?
    
       override func viewDidLoad() {
           super.viewDidLoad()
           bindUi()
       }
    
       func bindUi() {
           loginBtn.rx.action = vm!.loginAction
       }
    }
    
    class ViewModel {
    
      let loginAction: CococaAction = CocoaAction {
        // do something
      }
    }
    

提交回复
热议问题