2012-06-08 126 views
3

我對iOS SDK比較陌生,我正在遇到一個非常奇怪的問題,關於我正在開發的應用的設備鍵盤位置和方向。問題在於,如果在用戶多任務或應用程序進入後臺時打開鍵盤,用戶返回應用程序後,鍵盤將被移位(UIKeyboardWillChangeFrameNotification被擡起),但方向不正確並且位置。iOS鍵盤的位置和方向

有時鍵盤也完全脫離屏幕,這是完全不受歡迎的行爲。

我的問題是:

  1. 什麼是鍵盤的位置和方向依賴?它如何由iOS控制?

  2. 有沒有辦法檢測鍵盤在屏幕外顯示時間,而不考慮設備類型和屏幕大小?我認爲這可以通過跟蹤UIKeyboardWillChangeFrameNotificationUIKeyboardWillShowNotification來實現。

  3. 如何在顯示之前重置/設置鍵盤的位置和方向?這甚至有可能嗎?

回答

1

1.)鍵盤是一個UIWindow,位置取決於應用程序的主窗口。

2.)您可以做的是,在通知UIKeyboardWillShowNotificationUIKeyboardWillChangeFrameNotification方法觸發之一時,循環瀏覽windows子視圖以找到鍵盤。在我的一個應用程序中,我需要在鍵盤上添加一個子視圖。對於你的情況,你可以這樣做,得到的框架:

//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',您可以將自己的變換應用於。

這可能不是most優雅的解決方案,但它適用於我的情況。

希望這有助於!

+0

這是非常巧妙的解決辦法尋找鍵盤的位置。但出於某種原因,它似乎並不總能找到鍵盤。我已經在我的應用程序中遍歷了所有的'UIWindow',並且有時我什麼都沒有,即使鍵盤已經啓動。 – Zeenobit

+0

此外,關於您對問題1的回答:如果鍵盤位置僅取決於應用程序的主窗口,那麼在什麼情況下它會在主窗口外面彈出? – Zeenobit

5

從文檔:

可以使用「鍵盤通知用戶信息鍵」來描述獲得鍵盤從用戶信息詞典的位置和大小的關鍵。

鍵用於從鍵盤通知的用戶信息字典獲取值:

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