How can I subscribe to UIButton isSelected changes using RxSwift?

Viewed 1871

I am trying to have notifications when a button changes his 'isSelected' state. I have an UIButton setup with a target to change his isSelected:

let button = UIButton()
button.addTarget(button, action: #selector(toggleSelected), for: .touchUpInside)
....
@objc func toggleSelected() {
    self.isSelected = !self.isSelected
}

and I want to have something like button.rx.isSelectedChanged to be able to subscribe events.

I tried to extend UIButton.rx with a ControlProperty:

extension Reactive where Base: UIButton {

    public var isSelectedChanged: ControlProperty<Bool> {
        return base.rx.controlProperty(
            editingEvents:  [.allEditingEvents, .valueChanged],
            getter: { $0.isSelected },
            setter: { $0.isSelected = $1 })
    }

}

and something like:

button.rx.observe(Bool.self, "isSelected")
    .takeUntil(button.rx.deallocated)
    .subscribe(onNext: { print("selcted \($0)") })

but in neither way I have button.isSelected updates.

What is a good way of doing this?

EDIT: Following @daniel-t reply I implemented it here.

1 Answers

There's no good way of doing what you want and frankly, it's a mistake to try. The selected status of your button is changed programmatically for some reason. Don't try to store your model state in the UI, you should have the UI reflect your model state.

Look to whatever calls toggleSelected(). Likely that can be converted to rx and you can subscribe to it instead.

Related