问题
I used official two-way-binding solution
func <-> <T>(property: ControlProperty<T>, variable: Variable<T>) -> Disposable{
let bindToUIDisposable = variable.asObservable()
.bindTo(property)
let bindToVariable = property
.subscribe(onNext: { n in
variable.value = n
}, onCompleted: {
bindToUIDisposable.dispose()
})
return Disposables.create(bindToUIDisposable, bindToVariable)
}
Usage: (textField.rx.text <-> object.property).addDisposableTo(disposeBag)
Property definition: var property = Variable<String?>(nil)
- In onNext method all ok and
variable
changed its value, but myobject.property
doesn't changed. - Is there any way to set variable current value into ControlProperty inside of <-> method, bcs I need set initial value, before subscribe starts?
回答1:
My fault. I replaced object with another instance after binding
This code works well and control property receive initial value from variable
回答2:
Working in Swift 4
Example of two way binding between String & Textfield with MVVM architecture:
- In ViewController:
@IBOutlet weak var emailTextfield: UITextField!
var viewModel : CCRegisterViewModel?
- In ViewModel:
var email = Variable<String>("")
- Use this code in ViewController
viewModel?.email.asObservable()
.bind(to: emailTextfield.rx.text)
.disposed(by: disposeBag)
emailTextfield.rx.text.orEmpty.bind(to:viewModel!.email)
.disposed(by: disposeBag)
来源:https://stackoverflow.com/questions/43323049/rxswift-two-way-binding