使用RxSwift将多个UITextField绑定到一个类props

时间:2019-11-07 06:57:48

标签: ios swift mvvm rx-swift

我愿意将RxSwift用于模型值和视图控制器之间的MVVM绑定。我想将表单字段绑定到类属性。例如:

struct UserDetail {

    var firstName: String?
    var lastName: String?
    var nickName: String?
    var email: String?
    var nationalId: String?
    var birthday: String?


    init?() {}
}

现在我想将此类的实例绑定到我的UITextFields上,并在ViewModel中像这样定义它:

var userData = UserDetail()
userData.firstName = "myFirstName"

var userDetail = BehaviorSubject<UserDetail?>(value: userData)

目前,我不知道如何实现ViewController。

1 个答案:

答案 0 :(得分:1)

单独绑定每个属性而不是整个UserDetail对象可能是一个更好的主意,但是如果必须这样做,则可以在视图控制器中尝试以下操作:

// bind to view:
Observable.combineLatest(
    myView.firstNameTextField.rx.text,
    myView.lastNameTextField.rx.text,
    myView.nickNameTextField.rx.text,
    myView.emailTextField.rx.text,
    myView.nationalIdTextField.rx.text,
    myView.birthdayTextField.rx.text
)
.map {
    let userDetail = UserDetail()
    userDetail.firstName = $0
    userDetail.lastName = $1
    userDetail.nickName = $2
    userDetail.email = $3
    userDetail.nationalId = $4
    userDetail.birthday = $5
    return userDetail
}
.bind(to: viewModel.userDetail)
.disposed(by: disposeBag)

// bind to viewModel:
viewModel.userDetail
    .map { $0.firstName }
    .distinctUntilChanged()  // you may consider omitting this part
    .bind(to: myView.firstNameTextField.rx.text)
    .disposed(by: disposeBag)

viewModel.userDetail
    .map { $0.lastName }
    .distinctUntilChanged()
    .bind(to: myView.lastNameTextField.rx.text)
    .disposed(by: disposeBag)

// ... and so on