如何可靠地检测iOS 9是否连接了外部键盘? [英] How to reliably detect if an external keyboard is connected on iOS 9?

查看:253
本文介绍了如何可靠地检测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.

仍然可以检测键盘高度并判断显示的是较小的工具栏还是较大的虚拟键盘.但是,此方法不可靠,因为键盘高度已在各个beta之间更改,并且不能指望随着时间的推移保持不变.

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是否连接了外部键盘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆