使用RxSwift处理键盘WillHide



我想在键盘隐藏时启用一个按钮。如何使用rxSwift完成此操作?我尝试过这个代码,但从未调用过闭包:

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

Daniel的答案是正确的,可能是最简单的方法,但这里有另一个使用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模式非常简单,isCancelEnabled在ViewModel中声明,cancelButton在ViewController中"驱动"。

附言:我认为你不想像Daniel建议的那样包含.take(1(,因为这对第一个活动来说很好,但随后订阅将被处理,它将不再有效。

Observables不会做任何事情,除非它们被订阅。由于您没有使用subscribe(或bind,即如果观察到错误则断言的subscribe(,Observer没有做任何事情。这有点像创建一个对象,但从不调用它的任何函数。

我会这样写:

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)

最新更新