如何可靠地检测 iOS 9 上是否连接了外部键盘?

时间:2023-02-01
本文介绍了如何可靠地检测 iOS 9 上是否连接了外部键盘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在 iOS 9 之前,确定是否连接了外部键盘的最可靠方法是侦听 UIKeyboardWillShowNotification 并将文本字段设置为第一响应者,如 这个问题.使用虚拟键盘时会触发通知,但使用外部键盘时不会触发.

Previous to iOS 9, the most reliable method of determining whether an external keyboard is connected was to listen for UIKeyboardWillShowNotification and make a text field the first responder, as discussed in this question. The notification would fire when using the virtual keyboard, but would not fire when using an external keyboard.

然而,这种行为现在在 iOS 9 中有所改变.UIKeyboardWillShowNotification 也会在连接外部键盘时触发,因为现在会显示新的键盘工具栏.

However this behavior has now changed with iOS 9. UIKeyboardWillShowNotification also fires when an external keyboard is connected, since the new keyboard toolbar is now shown.

仍然可以检测键盘高度并判断显示的是较小的工具栏还是较大的虚拟键盘.然而,这种方法并不可靠,因为键盘高度在各个测试版之间发生了变化,并且不能指望随着时间的推移保持不变.

It is still possible to detect the keyboard height and make a judgement whether it is the smaller toolbar or the larger virtual keyboard that is being shown. However this method is not reliable since the keyboard height has changed between the various beta and can't be counted on to stay the same over time.

有没有更可靠的方法可以在 iOS 9 上使用?

Is there a more reliable method that can be used with iOS 9?

推荐答案

回到原来的问题后,我找到了一个可行的解决方案.

After going back to the original question, I've found a solution that works.

当显示常规虚拟键盘时,键盘框架似乎在屏幕的尺寸范围内.但是,当连接物理键盘并显示键盘工具栏时,键盘框架位于屏幕外.我们可以检查键盘框架是否在屏幕外,以确定键盘工具栏是否正在显示.

It seems that when the regular virtual keyboard is displayed the keyboard frame is within the dimensions of the screen. However when a physical keyboard is connected and the keyboard toolbar is displayed, the keyboard frame is located offscreen. We can check if the keyboard frame is offscreen to determine if the keyboard toolbar is showing.

Objective-C

- (void) keyboardWillShow:(NSNotification *)notification {
    NSDictionary* userInfo = [notification userInfo];
    CGRect keyboardFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGRect keyboard = [self.view convertRect:keyboardFrame fromView:self.view.window];
    CGFloat height = self.view.frame.size.height;

    if ((keyboard.origin.y + keyboard.size.height) > height) {
        self.hasKeyboard = YES;
    }
}

斯威夫特

@objc func keyboardWillShow(_ notification: NSNotification) {
    guard let userInfo = notification.userInfo else {return}
    let keyboardScreenEndFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
    let keyboard = self.view.convert(keyboardScreenEndFrame, from: self.view.window)
    let height = self.view.frame.size.height
    if (keyboard.origin.y + keyboard.size.height) > height {
        self.hasKeyboard = true
    }
}

这篇关于如何可靠地检测 iOS 9 上是否连接了外部键盘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:如何在 iOS 7 上模拟键盘动画以添加“完成"数字键盘的按钮? 下一篇:出现键盘时如何在iOS上调整UITextView的大小?

相关文章

最新文章