一般來說,鍵盤遮擋主要有這麼幾種情況,一個是遮住UITextView,還有就是遮住UITextField,一 般來說,比較推薦在UIScrollView或者UITableView裡加入textfield的控制項。但是有時也許難免。
在UITextView中
這個在蘋果官方文檔中的項目中給出了做法,首先是註冊觀察者監聽 UIKeyboardWillShow和WillHide事件
- (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil]; }
實現自訂的方法
- (void)keyboardWillShow:(NSNotification *)aNotification { NSDictionary *userInfo = [aNotification userInfo]; CGRect keyboardRect = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue]; NSTimeInterval animationDuration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]; CGRect newFrame = self.view.frame; newFrame.size.height -= keyboardRect.size.height; [UIView beginAnimations:@"ResizeTextView" context:nil]; [UIView setAnimationDuration:animationDuration]; self.view.frame = newFrame; [UIView commitAnimations]; }
擷取鍵盤顯示的資訊,然後根據資訊對view的frame進行調整,然後WillHide方法就跟上面相 同,只不過把高度新高度改成+= keyboardRect.size.height就可以了,最後,移除觀察者:
- (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil]; [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil]; }