The range together with the control domain rx promoted to the monand domain, and then bind.
Type promotion.
In the previous article sample, all bindings are one-way. But sometimes we need to implement two-way binding. For example, the value of a property control and ViewModel
in certain Subject
attributes two-way binding:
- So that when
ViewModel
the time changes in the value can be synced to the control. - And if making changes to the control value,
ViewModel
there value will also change.
A simple two-way binding
1, the effect of FIG.
(1) top of the page is a text entry box for the user to fill in name. It VM
was the username
property to do two-way binding.
Text label (2) below will be based on the user information corresponding to the user name is displayed. (Only hangge display administrator, all other visitors)
2, sample code
(1) a first defined VM
, as follows:
import RxSwift
struct UserViewModel {
//用户名 let username = Variable("guest") //用户信息 lazy var userinfo = { return self.username.asObservable() .map{ $0 == "hangge" ? "您是管理员" : "您是普通访客" } .share(replay: 1) }() }
(2) the following page code (highlight part of textfield
the VM
two-way binding):
import UIKit
import RxSwift
import RxCocoa
class ViewController: UIViewController {
@IBOutlet weak var textField: UITextField! @IBOutlet weak var label: UILabel! var userVM = UserViewModel() let disposeBag = DisposeBag() override func viewDidLoad() { //将用户名与textField做双向绑定 userVM.username.asObservable().bind(to: textField.rx.text).disposed(by: disposeBag) textField.rx.text.orEmpty.bind(to: userVM.username).disposed(by: disposeBag) //将用户信息绑定到label上 userVM.userinfo.bind(to: label.rx.text).disposed(by: disposeBag) } }
Second, custom bidirectional binding operator (operator)
1, RxSwift operator comes way binding
(1) If the regular two-way binding, it is best to customize a operator
user-friendly.
(2) Fortunately, the RxSwift
project folder already has a ready-made ( Operators.swift
), we can copy it to our project. Of course, as we want to write some other way binding operator
can also refer to it.
2, using the sample
Two-way binding operator is: <->
. We modify our example, the code can be found to streamline a lot.
import UIKit
import RxSwift
import RxCocoa
class ViewController: UIViewController {
@IBOutlet weak var textField: UITextField! @IBOutlet weak var label: UILabel! var userVM = UserViewModel() let disposeBag = DisposeBag() override func viewDidLoad() { //将用户名与textField做双向绑定 _ = self.textField.rx.textInput <-> self.userVM.username //将用户信息绑定到label上 userVM.userinfo.bind(to: label.rx.text).disposed(by: disposeBag) } }
RxSwift uses detailed series
From the original: www.hangge.com reproduced please retain the original link
Author: eight large wind AM
link: https: //www.jianshu.com/p/39fb6a65ec91
Source: Jane book
Jane book copyright reserved by the authors, are reproduced in any form, please contact the author to obtain authorization and indicate the source.