以前的做法和這個比起來簡直就是xxxx,今天看官方的參考庫又學了一招~
以前的實現效果和這個是一樣,不過代碼上比這個多了點
程序清單5-1 處理鍵盤通告
// Call this method somewhere in your view controller setup code. |
- (void)registerForKeyboardNotifications |
{ |
[[NSNotificationCenter defaultCenter] addObserver:self |
selector:@selector(keyboardWasShown:) |
name:UIKeyboardDidShowNotification object:nil]; |
[[NSNotificationCenter defaultCenter] addObserver:self |
selector:@selector(keyboardWasHidden:) |
name:UIKeyboardDidHideNotification object:nil]; |
} |
// Called when the UIKeyboardDidShowNotification is sent. |
- (void)keyboardWasShown:(NSNotification*)aNotification |
{ |
if (keyboardShown) |
return; |
NSDictionary* info = [aNotification userInfo]; |
// Get the size of the keyboard. |
NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey]; |
CGSize keyboardSize = [aValue CGRectValue].size; |
// Resize the scroll view (which is the root view of the window) |
CGRect viewFrame = [scrollView frame]; |
viewFrame.size.height -= keyboardSize.height; |
scrollView.frame = viewFrame; |
// Scroll the active text field into view. |
CGRect textFieldRect = [activeField frame]; |
[scrollView scrollRectToVisible:textFieldRect animated:YES]; |
keyboardShown = YES; |
} |
// Called when the UIKeyboardDidHideNotification is sent |
- (void)keyboardWasHidden:(NSNotification*)aNotification |
{ |
NSDictionary* info = [aNotification userInfo]; |
// Get the size of the keyboard. |
NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey]; |
CGSize keyboardSize = [aValue CGRectValue].size; |
// Reset the height of the scroll view to its original value |
CGRect viewFrame = [scrollView frame]; |
viewFrame.size.height += keyboardSize.height; |
scrollView.frame = viewFrame; |
keyboardShown = NO; |
} |
上面程序清單中的keyboardShown
變量是一個布爾值,用於跟蹤鍵盤是否可見。如果您的用戶界面有多個文本輸入框,則用戶可能觸擊其中的任意一個進行編輯。發生這種情況時,雖然鍵盤並不消失,但是每次開始編輯新的文本框時,系統都會產生UIKeyboardDidShowNotification
通告。您可以通過跟蹤鍵盤是否確實被隱藏來避免多次減少滾動視圖的尺寸。
程序清單5-2顯示了一些額外的代碼,視圖控制器用這些代碼來設置和清理之前例子中的activeField
變量。在初始化時,界面中的每個文本框都將視圖控制器設置為自己的委托。因此,當文本編輯框被激活的時候,這些方法就會被調用。更多關於文本框及其委托通告的信息,請參見UITextField類參考。
程序清單5-2 跟蹤活動文本框的方法
- (void)textFieldDidBeginEditing:(UITextField *)textField |
{ |
activeField = textField; |
} |
- (void)textFieldDidEndEditing:(UITextField *)textField |
{ |
activeField = nil; |
} |