在 iOS5 上請求顯示鍵盤時,系統從屏幕底部將鍵盤滑入上來,位于應用的內容之上。
(墻內:http://mikixiyou.VEvb.com/blog/1488302)
如果屏幕中的內容項目比較多,它就可能覆蓋住文本輸入框之類的對象。你必須調整你的內容,使得輸入框保持可見。
你會想到哪些處理方法呢?
第一種,
臨時調整窗口中各個視圖的大小,使得鍵盤從下向上占領的區域空白。鍵盤的高度( keyboard.size.height )是一定的,將視圖中所有內容所在區域的 y 值減小到 y-keyboard.size.height 。
該方法有個局限,如果所有內容之和大于窗口減去鍵盤高度的話,該方法將不能用。
第二種,
將窗口中所有視圖嵌入進一個滾動視圖對象( UIScrollView )中。在鍵盤出現時,你將輸入框滾動到合適的位置,調整一下滾動視圖的內容區域。
這些操作通過一個通知 UIKeyboardDidShowNotification 去實現的,邏輯過程如下:
1 、根據通知的字典信息 userInfo 得到鍵盤的 size 。
2 、根據鍵盤的 size 中的 height 值,調整滾動視圖內容底部的 inset 。
3 、滾動目標視圖即文件輸入框進入視圖中。
簡要的代碼如下:
1 、實現兩個委托方法,用于指定輸入框對象。
- (void)textFieldDidBeginEditing:(UITextField *)textField |
{ |
activeField = textField; |
} |
- (void)textFieldDidEndEditing:(UITextField *)textField |
{ |
activeField = nil; |
} |
2 、注冊通知的觀察者
- (void)registerForKeyboardNotifications |
{ |
[[NSNotificationCenter defaultCenter] addObserver:self |
selector:@selector(keyboardWasShown:) |
name:UIKeyboardDidShowNotification object:nil]; |
[[NSNotificationCenter defaultCenter] addObserver:self |
selector:@selector(keyboardWillBeHidden:) |
name:UIKeyboardWillHideNotification object:nil]; |
} |
將這個方法放在 viewDidAppear 中調用。
同時也要寫一個 removeObserver 放在 viewWillDisappear 中調用。
3 、實現鍵盤顯示通知的 selector 中的方法
// Called when the UIKeyboardDidShowNotification is sent. |
- (void)keyboardWasShown:(NSNotification*)aNotification |
{ |
NSDictionary* info = [aNotification userInfo]; |
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size; |
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0); |
scrollView.contentInset = contentInsets; |
scrollView.scrollIndicatorInsets = contentInsets; |
// If active text field is hidden by keyboard, scroll it so it's visible |
// Your application might not need or want this behavior. |
CGRect aRect = self.view.frame; |
aRect.size.height -= kbSize.height; |
if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) { |
CGPoint scrollPoint = CGPointMake(0.0, activeField.frame.origin.y-kbSize.height); |
[scrollView setContentOffset:scrollPoint animated:YES]; |
} |
} |
4 、實現鍵盤消失通知的方法
// Called when the UIKeyboardWillHideNotification is sent |
- (void)keyboardWillBeHidden:(NSNotification*)aNotification |
{ |
UIEdgeInsets contentInsets = UIEdgeInsetsZero; |
scrollView.contentInset = contentInsets; |
scrollView.scrollIndicatorInsets = contentInsets; |
} |
這個方法調整內容底部的 inset 的值使得輸入框不被鍵盤區域屏蔽的。還可以換種方法實現。
第三種,
擴展內容視圖的高度,滾動文本輸入框對象進內容視圖。
將 keyboardWasShown: 重寫。
- (void)keyboardWasShown:(NSNotification*)aNotification { |
NSDictionary* info = [aNotification userInfo]; |
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size; |
CGRect bkgndRect = activeField.superview.frame; |
bkgndRect.size.height += kbSize.height; |
[activeField.superview setFrame:bkgndRect]; |
[scrollView setContentOffset:CGPointMake(0.0, activeField.frame.origin.y-kbSize.height) animated:YES]; |
} |
新聞熱點
疑難解答