I want to bind UIButton
title to a BehaviorSubject<String>
in my ViewModel. I do it in Label
like below:
//ViewModel
var fullName = BehaviorSubject<String?>(value: "")
//ViewController
vm.fullName.bind(to: fullNameLabel.rx.text).disposed(by: bag)
is there any way to do this?
The correct way is to use the title()
binder.
vm.fullName
.bind(to: button.rx.title())
.disposed(by: disposeBag)
Following RxCocoa
, Reactive
also extend UIButton title
or attributedTitle
to bind it
Please check this [RxSwift/UIButton+Rx.swift] link (https://github.com/ReactiveX/RxSwift/blob/master/RxCocoa/iOS/UIButton%2BRx.swift)
extension Reactive where Base: UIButton {
/// Reactive wrapper for `setTitle(_:for:)`
public func title(for controlState: UIControl.State = []) -> Binder<String?> {
return Binder(self.base) { button, title -> Void in
button.setTitle(title, for: controlState)
}
}
}
extension Reactive where Base: UIButton {
/// Reactive wrapper for `setAttributedTitle(_:controlState:)`
public func attributedTitle(for controlState: UIControl.State = []) -> Binder<NSAttributedString?> {
return Binder(self.base) { button, attributedTitle -> Void in
button.setAttributedTitle(attributedTitle, for: controlState)
}
}
}
So you can bind your full name BehaviorSubject to button like your sample code label
vm.fullName.bind(to: someButton.rx.title()).disposed(by: bag)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With