如何创建一个发射键盘高度的 RxSwift Observable?

Lau*_*oki 3 ios rx-swift

我想观察 iOS 键盘的高度。我如何使用 RxSwift 做到这一点?

tom*_*ahh 7

如果你只对键盘的高度感兴趣,可以观察UIKeyboardDidChangeFrame通知

let keyboardHeight = NotificationCenter.default.rx
  .notification(NSNotification.Name.UIKeyboardDidChangeFrame)
  .map { notification -> CGFloat in
    (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.height ?? 0
  }
Run Code Online (Sandbox Code Playgroud)

请注意,在这里,即使离开屏幕,键盘的高度也将保持“满”状态。这些通知仅对由于键盘语言更改或显示/隐藏自动完成按钮而导致的帧更改有用。

如果您想考虑键盘的边框为0当它的屏幕,你可以结合上述观察到与UIKeyboardWillShowUIKeyboardHide通知。

let keyboardOnScreenHeight = Observable.from([
  NotificationCenter.default.rx.notification(NSNotification.Name.UIKeyboardWillShow)
    .flatMap { _ in keyboardHeight }
  NotificationCenter.default.rx.notification(NSNotification.Name.UIKeyboardWillHide)
    .map { _ in 0 }
])
.merge()
Run Code Online (Sandbox Code Playgroud)

由此,您将获得先前定义的keyboardHeight在屏幕上时发出的值,以及 0 退出时发出的值。