title: Custom UIControl subclass with RxSwift
body: <p>I am creating a custom subclass of UIControl (I need to override its draw method) and I want to add RxSwift to bind its <strong>isSelected</strong> property to my model.</p>
  
  <p>So far so good. This works fine.</p>
  
  <p>My problem is how can I do to change the value <strong>isSelected</strong> property in response of user touchUpInside event?.</p>
  
  <p>My first try was to use the <strong>addTarget</strong> method of UIControl, but changing the value of <strong>isSelected</strong> programmatically is not reported by the ControlProperty (as stated in the doc). But I can figure another way to resolve this.</p>
  
  <p>Any help appreciated.</p>
  
  <p>Source code of the subclass:</p>
  
  <pre><code>class SYYesNoButton: UIControl {
  
  override init(frame: CGRect) {
      super.init(frame: frame)
  
      // subscribe to touchUpInside event
  
      addTarget(
          self,
          action: #selector(userDidTouchUpInside),
          for: UIControlEvents.touchUpInside)
  }
  
  
  
  func userDidTouchUpInside() {
  
      // change the value of the property
      // this does not work, 
      // the change is not reported to the ControlProperty
      // HOW CAN I CHANGE THIS ??
  
      self.isSelected = !isSelected
  }
  
  }
  </code></pre>
  
  <p>Extensions to add reactive support:</p>
  
  <pre><code>extension SYYesNoButton {
  
      var rx_isSelected: ControlProperty&lt;Bool&gt; {
  
      return UIControl.valuePublic(
          self,
          getter: { (button) -&gt; Bool in
              return button.isSelected
      },
          setter: { (button, value) in
              button.isSelected = value
      })
  
  
      }
  }
  
  
  
  extension UIControl {
  
      static func valuePublic&lt;T, ControlType: UIControl&gt;(_ control: ControlType, getter:  @escaping (ControlType) -&gt; T, setter: @escaping (ControlType, T) -&gt; ()) -&gt; ControlProperty&lt;T&gt; {
  
  
  
          let values: Observable&lt;T&gt; = Observable.deferred { [weak control] in
              guard let existingSelf = control else {
                  return Observable.empty()
              }
  
              return (existingSelf as UIControl).rx.controlEvent([.allEditingEvents, .valueChanged])
                  .flatMap { _ in
                      return control.map { Observable.just(getter($0)) } ?? Observable.empty()
                  }
                  .startWith(getter(existingSelf))
          }
  
  
          return ControlProperty(values: values, valueSink: UIBindingObserver(UIElement: control) { control, value in
              setter(control, value)
          })
  
      }
  }
  </code></pre>
  
  <p>Thanks for all.</p>