Search code examples
iosswiftrx-swiftrx-cocoa

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


Solution

  • 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})
        }
    
    }