Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a rx.value to my CustomView

Lets say i have a CustomView with a value in it. I want to expose that value to the world using rx.value (Observable) instead of having to access it by value (Int).

final class CustomView: UIView {
   var value: Int = 0
   ...
}

I copied this from UIStepper+Rx:

extension Reactive where Base: CustomView {

    var value: ControlProperty<Int> {
        return base.rx.controlProperty(editingEvents: [.allEditingEvents, .valueChanged],
            getter: { customView in
                customView.currentValue
        }, setter: { customView, value in
            customView.currentValue = value
        }
        )
    }

}

final class CustomView: UIControl {

    fileprivate var currentValue = 1 {
        didSet {
            checkButtonState()
            valueLabel.text = currentValue.description
        }
    }

   // inside i set currentValue = 3
}

But customView.rx.value doesnt emit any values

like image 697
Godfather Avatar asked Jun 21 '18 13:06

Godfather


1 Answers

The missing thing is, you need to send action on UIControl. Check the next example:

class CustomView: UIControl {
    var value: Int = 0 {
        didSet { sendActions(for: .valueChanged) } // You are missing this part
    }
}

extension Reactive where Base: CustomView {

    var value: ControlProperty<Int> {
        return base.rx.controlProperty(editingEvents: UIControlEvents.valueChanged,
                                       getter: { customView in
                                        return customView.value },
                                       setter: { (customView, newValue) in
                                        customView.value = newValue})
    }

}
like image 187
Evghenii Nicolaev Avatar answered Oct 23 '22 14:10

Evghenii Nicolaev