iOS 提供的如何编写 Reactive 扩展来观察字符串 属性 或父 class 中的变化

How to write a Reactive extension to observe the change in a string property or parent class, provided by iOS

我正在继承SLComposeServiceViewController。它有一个 contentText 字符串,其中包含在其中一个视图中输入的文本。我想写一个像 extension Reactive where Base: SLComposeServiceViewController 这样的扩展,以便能够观察到这个变量值的任何变化。

我找不到实现此目的的正确语法示例

我试过

extension Reactive where Base: SLComposeServiceViewController {
  public func controlProperty<T>(
    editingEvents: ControlProperty<String> ,
    getter: @escaping (Base) -> T,
    setter: @escaping (Base, T) -> Void
  ) -> ControlProperty<T> {

  }
}

SLComposeServiceViewController 没有提供观察 contentText 属性 的方法,所以 Rx 没有钩子可以用来将它包装到 Observable 中。然而,class' textView 属性 确实有这样一个钩子,并且 Observable 已经在 RxCocoa 中提供了。

试试这个:

extension Reactive where Base: SLComposeServiceViewController {
    public var contentText: ControlProperty<String> {
        return base.textView.rx.string // could be rx.text if you are using UIKit instead of AppKit
    }
}