iOS键盘位置和方向

3
我对iOS SDK还比较陌生,目前遇到了一个非常奇怪的问题,涉及设备键盘位置和方向,在我正在开发的应用中。问题是,如果用户在多任务处理或者应用进入后台时键盘处于打开状态,当用户回到应用时,键盘会被错位(触发UIKeyboardWillChangeFrameNotification),而且方向和位置不正确。
有时候键盘甚至完全显示在屏幕外面,这种行为完全不可接受。
我的问题如下:
  1. 键盘的位置和方向依赖于什么?它是如何被iOS控制的?

  2. 是否有一种方法可以检测键盘是否显示在屏幕外,而不考虑设备类型和屏幕大小?我认为可以通过跟踪UIKeyboardWillChangeFrameNotificationUIKeyboardWillShowNotification来实现。

  3. 在显示键盘之前,如何重置/设置键盘的位置和方向?这是否可能?

2个回答

5

根据文档:

使用“键盘通知用户信息键”中描述的键从userInfo字典中获取键盘的位置和大小。

用于从键盘通知的用户信息字典中获取值的键:

NSString * const UIKeyboardFrameBeginUserInfoKey;
NSString * const UIKeyboardFrameEndUserInfoKey;
NSString * const UIKeyboardAnimationDurationUserInfoKey;
NSString * const UIKeyboardAnimationCurveUserInfoKey;

1

1.) 键盘是一个UIWindow,其位置取决于应用程序的主窗口。

2.) 你可以在收到通知UIKeyboardWillShowNotificationUIKeyboardWillChangeFrameNotification后,通过循环遍历窗口的子视图来定位键盘。在我的一个应用程序中,我需要向键盘添加一个子视图。对于你的情况,你可以通过以下方式获取框架:

//The UIWindow that contains the keyboard view - It some situations it will be better to actually
//iterate through each window to figure out where the keyboard is, but In my applications case
//I know that the second window has the keyboard so I just reference it directly
UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];

//Because we cant get access to the UIPeripheral throught the SDK we will just use UIView.
//UIPeripheral is a subclass of UIView anyways
UIView* keyboard;

    //Iterate though each view inside of the selected Window
for(int i = 0; i < [tempWindow.subviews count]; i++)
{
    //Get a reference of the current view
    keyboard = [tempWindow.subviews objectAtIndex:i];

           //Assuming this is for 4.0+, In 3.0 you would use "<UIKeyboard"
           if([[keyboard description] hasPrefix:@"<UIPeripheral"] == YES) {

                  //Keyboard is now a UIView reference to the UIPeripheral we want
                  NSLog(@"Keyboard Frame: %@",NSStringFromCGRect(keyboard.frame));

           }
}

3.) 不完全确定这是否可行,但使用我给你的提供的代码,keyboard现在被转换为'UIView',您可以对其应用自己的变换。

这可能不是优雅的解决方案,但它在我的情况下运行良好。

希望这可以帮助!


这是一个非常不错的解决方案,可以找到键盘位置。但出于某种原因,它似乎并不能总是找到键盘。我已经让它遍历了我的应用程序中的所有UIWindow,有时候我什么也得不到,即使键盘已经弹出。 - Zeenobit
另外,关于你对第一个问题的回答:如果键盘位置仅取决于应用程序的主窗口,那么在什么情况下它会弹出主窗口之外? - Zeenobit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接