Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind my UIButton title to my ViewModel

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?

like image 949
J4L0O0L Avatar asked Jan 26 '23 15:01

J4L0O0L


2 Answers

The correct way is to use the title() binder.

vm.fullName
    .bind(to: button.rx.title())
    .disposed(by: disposeBag)
like image 102
Daniel T. Avatar answered Jan 29 '23 23:01

Daniel T.


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)
like image 37
Cruz Avatar answered Jan 30 '23 01:01

Cruz