How to reliably detect if an external keyboard is connected on iOS 9?

前端 未结 9 713
隐瞒了意图╮
隐瞒了意图╮ 2020-12-02 13:05

Previous to iOS 9, the most reliable method of determining whether an external keyboard is connected was to listen for UIKeyboardWillShowNotification and make a

9条回答
  •  时光取名叫无心
    2020-12-02 13:45

    I am using a variation on Sarah Elan's answer. I was having issues with her approach in certain views. I never quite got to the bottom of what caused the problem. But here is another way to determine if it is an ios9 external keyboard 'undo' bar that you have, rather than the full sized keyboard.

    It is probably not very forward compatible since if they change the size of the undo bar, this brakes. But, it got the job done. I welcome criticism as there must be a better way...

    //... somewhere ...
    #define HARDWARE_KEYBOARD_SIZE_IOS9 55 
    //
    
    + (BOOL) isExternalKeyboard:(NSNotification*)keyboardNotification {
    
      NSDictionary* info = [keyboardNotification userInfo];
      CGRect keyboardEndFrame;
      [[info valueForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardEndFrame];
      CGRect keyboardBeginFrame;
      [[info valueForKey:UIKeyboardFrameBeginUserInfoKey] getValue:&keyboardBeginFrame];
    
      CGFloat diff = keyboardEndFrame.origin.y - keyboardBeginFrame.origin.y;
      return fabs(diff) == HARDWARE_KEYBOARD_SIZE_IOS9;
    }
    

提交回复
热议问题