【问题标题】:Swift how to detect if keyboard is fully visible or fully hidden only (and not partially visible)Swift 如何检测键盘是完全可见还是完全隐藏(而不是部分可见)
【发布时间】:2021-01-17 17:29:04
【问题描述】:

这个问题与以下问题有关:Detect when keyboard is fully visible and prevent keyboard appearance handling code from adding extra offset for hidden element

我最初使用NSNotification.Name.UIKeyboardDidShowNSNotification.Name.UIKeyboardDidHide 之类的通知,希望它们只会被触发一次,因此我可以设置一个布尔值,即键盘完全显示或隐藏。

但我注意到,所有事件:UIKeyboardWillShowUIKeyboardDidShowUIKeyboardWillHideUIKeyboardDidHideUIKeyboardWillChangeFrameUIKeyboardDidChangeFrame 都设计为在键盘出现或消失时多次触发。

似乎没有办法检查键盘是完全可见还是部分不可见。我查看的所有答案都听取了这些通知并进行了计算以避免视图被键盘隐藏。但是我找不到任何方法来查看键盘是否完全显示(或完全隐藏)

我什至查看了KeyboardObserver,它可以更容易地观察键盘事件,但是由于它仍然基于默认通知,它的 KeyboardEventType.didShow 和 KeyboardEventType.didHide 在键盘出现和消失时会被多次触发。

应该有更好的方法来判断键盘是完全可见还是不可见!

【问题讨论】:

  • 只是一个想法,虽然我从未尝试过。 UIKeyboardWillChangeFrame 为您提供屏幕坐标中的键盘框架。你看不出这个框架是否与屏幕的框架完全相交?您必须使用一些 CGRect 翻译和计算:developer.apple.com/documentation/coregraphics/cgrect/…
  • 我尝试使用末端框架,但它的高度是可变的,所以我也不能真正使用它。还有其他属性可以给我最终的键盘高度吗?

标签: ios swift nsnotificationcenter uikeyboard


【解决方案1】:
extension UIApplication {
var isKeyboardPresented: Bool {
    if let keyboardWindowClass = NSClassFromString("UIRemoteKeyboardWindow"),
        self.windows.contains(where: { $0.isKind(of: keyboardWindowClass) }) {
        return true
    } else {
        return false
    }
}

}

    if UIApplication.shared.isKeyboardPresented {
     print("Keyboard presented") }
 else { 
     print("Keyboard is not presented")
}

【讨论】:

  • 不错的技巧,但这会依赖私有 API,并且可能在未来的任何时候中断。
  • 这是哪个私有api?
  • 他指的是UIRemoteKeyboardWindow,这是不公开的。
猜你喜欢
  • 2013-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-30
  • 1970-01-01
  • 2018-04-21
  • 2016-05-15
  • 2021-11-24
相关资源
最近更新 更多