繁体   English   中英

使用 RxSwift 处理键盘WillHide

[英]Use RxSwift to handle the keyboardWillHide

我想在键盘隐藏时启用一个按钮。 如何使用 rxSwift 做到这一点? 我尝试了这段代码,但从未调用过闭包:

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

除非订阅,否则 Observable 不会做任何事情。 由于您没有使用subscribe (或bind ,它是一个断言如果观察到错误的subscribe ),观察者没有做任何事情。 这有点像创建 object 但从不调用它的任何函数。

我会这样写:

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)

丹尼尔的回答是正确的,可能是最简单的方法,但这里是另一个使用 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)

这可能是一个稍长的版本,但现在使用 MVVM 模式非常简单,在 ViewModel 中声明 isCancelEnabled 并在 ViewController 中声明 cancelButton 'driving'。

PS 我不认为你想像 Daniel 所建议的那样包含 the.take(1) ,因为这对于第一个事件来说可以正常工作,但随后订阅将被处理并且它将不再工作。

暂无
暂无

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

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