移除iOS虛擬鍵盤上的下ㄧ個與上一個按鈕

在iOS上需要輸入資訊的時候,會自動跳出一個虛擬鍵盤。鍵盤上方會有一排按鈕:上一個  / 下 一個 / 完成。有時候很有用,但是有時候很惱人。如果你的App會因為未知的下一個導致行為亂跳的會可能會很麻煩。原本覺得應該是模擬鍵盤的Tab,但是收keydown的時候並沒有任何事件發生,所以大概是iOS自己做掉了。因此要解決亂跳的問題就只能把這一排按鈕幹掉。

首先必須知道鍵盤出現的時間點,在 viewDidLoad 的函式中加入:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

這樣就可以註冊一個observer,在鍵盤要出現的時候會呼叫我們定義的keyboardWillShow method:

- (void)keyboardWillShow:(NSNotification *)note {
    [self performSelector:@selector(removeBar) withObject:nil afterDelay:0];
}

這邊需要一個短暫的delay再去呼叫removeBar,因為在收到的當下鍵盤的view還沒實際出現。不過這樣一來就有可能執行removeBar的時候鍵盤其實還沒出現(我反覆測試了很多次,都還沒遇到有失敗的case)。

實際上真正移除的code如下,先找到非UI-Window的keyboardWindow,之後在從keyboard的subviews裡面找到鍵盤上方的按鈕subview:

- (void)removeBar {
    // Locate non-UIWindow.
    UIWindow *keyboardWindow = nil;
    for (UIWindow *testWindow in [[UIApplication sharedApplication] windows]) {
        if (![[testWindow class] isEqual:[UIWindow class]]) {
            keyboardWindow = testWindow;
            break;
        }
    }

    // Locate UIWebFormView.
    for (UIView *possibleFormView in [keyboardWindow subviews]) {       
        // iOS 5 sticks the UIWebFormView inside a UIPeripheralHostView.
        if ([[possibleFormView description] rangeOfString:@"UIPeripheralHostView"].location != NSNotFound) {
            for (UIView *subviewWhichIsPossibleFormView in [possibleFormView subviews]) {
                if ([[subviewWhichIsPossibleFormView description] rangeOfString:@"UIWebFormAccessory"].location != NSNotFound) {
                    [subviewWhichIsPossibleFormView removeFromSuperview];
                }
            }
        }
    }
}

此文參考:A one stop blog for iPhone Application Development

Tags:


Leave a Reply

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *