简体   繁体   English

使用 RxSwift 处理键盘WillHide

[英]Use RxSwift to handle the keyboardWillHide

I would like to enable a button when the keyboard is hidden.我想在键盘隐藏时启用一个按钮。 How can I do this using rxSwift?如何使用 rxSwift 做到这一点? I tried this code but the closure is never called:我尝试了这段代码,但从未调用过闭包:

NotificationCenter.default.rx.notification(UIResponder.keyboardWillHideNotification)
    .map { _ in if let cancelButton = self.searchBar.value(forKey: "cancelButton") as? UIButton {
    cancelButton.isEnabled = true
} }

Observables don't do anything unless they are subscribed to.除非订阅,否则 Observable 不会做任何事情。 Since you did not use a subscribe (or bind which is a subscribe that asserts if an error is observed) the Observer didn't do anything.由于您没有使用subscribe (或bind ,它是一个断言如果观察到错误的subscribe ),观察者没有做任何事情。 It's kind of like creating an object but never calling any of its functions.这有点像创建 object 但从不调用它的任何函数。

I would write it like this:我会这样写:

let cancelButton = searchBar.value(forKey: "cancelButton") as! UIButton
NotificationCenter.default.rx.notification(UIResponder.keyboardWillHideNotification)
    .map { _ in true }
    .take(1)
    .subscribe(cancelButton.rx.isEnabled)
    .disposed(by: disposeBag)

Daniel's answer is correct and probably the simplest way of doing it, but here is another example of doing the same thing using RxCocoa:丹尼尔的回答是正确的,可能是最简单的方法,但这里是另一个使用 RxCocoa 做同样事情的例子:

let keyboardShown = NotificationCenter.default.rx.notification(UIResponder.keyboardWillShowNotification)
let keyboardHidden = NotificationCenter.default.rx.notification(UIResponder.keyboardWillHideNotification)

let isCancelEnabled = Observable.merge(keyboardShown.map { _ in false }, keyboardHidden.map { _ in true })
    .startWith(false)
    .asDriver(onErrorJustReturn: false)

let cancelButton = searchBar.value(forKey: "cancelButton") as! UIButton

isCancelEnabled
    .drive(cancelButton.rx.isEnabled)
    .disposed(by: disposeBag)

This might be a slightly longer version of doing it but it is now very simple to employ an MVVM pattern, with the isCancelEnabled being declared in the ViewModel and cancelButton 'driving' in the ViewController.这可能是一个稍长的版本,但现在使用 MVVM 模式非常简单,在 ViewModel 中声明 isCancelEnabled 并在 ViewController 中声明 cancelButton 'driving'。

PS I don't think you want to include the.take(1) as suggested by Daniel as this will work fine for the first event but then the subscription will get disposed and it will no longer work. PS 我不认为你想像 Daniel 所建议的那样包含 the.take(1) ,因为这对于第一个事件来说可以正常工作,但随后订阅将被处理并且它将不再工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM