首先必須知道鍵盤出現的時間點,在 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