【问题标题】:how to subscribe to a UITextView in iOS swift?如何在 iOS swift 中订阅 UITextView?
【发布时间】:2021-08-12 15:29:51
【问题描述】:

我是 IOS 开发的新手,正在做一个小项目,我正在尝试使用 Rxswift 订阅 UITextView。但是,我似乎无法在网上或按照我对 UITextField 所做的操作找到任何方法。

这就是我所做的及其对 TextField 的工作:

TextField.rx.controlEvent(.editingChanged).withLatestFrom(textField.rx.text.orEmpty)subscribe(onNext : { text in
        self.viewModel.address.accept(text)
Some code goes here

现在对 textView 做同样的事情

TextView.rx.controlEvent(.editingChanged).withLatestFrom(TextView.rx.text.orEmpty)subscribe(onNext : { text in
    self.viewModel.address.accept(text)

我收到以下错误: 在 'Reactive' 上引用实例方法 'controlEvent' 要求 'UITextView' 继承自 'UIControl'

我真的很困惑如何使 controlEvent 与 UITextField 一起工作。当我使用 rx 时,它不会显示在建议的代码中。

【问题讨论】:

    标签: ios swift uitextview rx-swift uitextviewdelegate


    【解决方案1】:

    这比你的问题要容易得多......

    func example(textView: UITextView, textField: UITextField, disposeBag: DisposeBag) {
        textView.rx.text
            .subscribe(onNext: { print($0) })
            .disposed(by: disposeBag)
        textField.rx.text
            .subscribe(onNext: { print($0) })
            .disposed(by: disposeBag)
    }
    

    您的订阅也可以简单得多:

    func example(textView: UITextView, observer: PublishRelay<String>, disposeBag: DisposeBag) {
        textView.rx.text
            .orEmpty
            .bind(to: observer)
            .disposed(by: disposeBag)
    }
    

    但是,请记住:

    主题 [和中继] 提供了一种在 Rx 周围进行探索的便捷方式,但不建议将它们用于日常使用。解释在附录中的Usage Guidelines 中。不要使用主题,而是支持我们将在Part 2 中看到的工厂方法。 -- Intro to Rx

    现在改掉将所有内容绑定到 Relay 或 Subject 的习惯,你会发现你在 Rx 中的未来变得更加容易。

    【讨论】:

    • 谢谢!!!救生员!!这很清楚。我将查看使用指南,以便更清楚地了解使用它的最佳方式。
    猜你喜欢
    • 1970-01-01
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-08
    相关资源
    最近更新 更多