鍵盤遮擋控制項(textfield/textview.......),textfieldtextview
採用的是通知的常規方式
// 解決鍵盤遮擋問題
//選擇didShow是因為需要鍵盤的高度
//選擇willHide是因為視圖frame重設需要優先於鍵盤消失,否則表現得不連貫
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHide:) name:UIKeyboardWillHideNotification object:nil];
觸發的方法
-(void)keyboardWasShown:(NSNotification*)notification{ //擷取鍵盤高度 NSValue* value=notification.userInfo[UIKeyboardFrameBeginUserInfoKey]; CGFloat keyBoradHeight=[value CGRectValue].size.height; NSNumber* animationTime=notification.userInfo[UIKeyboardAnimationDurationUserInfoKey]; double time=[animationTime doubleValue]; //擷取被遮擋控制項距離controller底部的距離 float a=self.view4.frame.origin.y+self.view4.frame.size.height; float b = self.view.frame.size.height-a; if (b<keyBoradHeight) { //動畫效果 [UIView animateWithDuration:time animations:^ { //鍵盤被擋住了 CGRect viewCGrect=self.view.frame; //視圖應該上移所以是- viewCGrect.origin.y=viewCGrect.origin.y-(keyBoradHeight-b); [self.view setFrame:viewCGrect]; } completion:nil]; }}-(void)keyboardWasHide:(NSNotification*)notification{ NSValue* value=notification.userInfo[UIKeyboardFrameBeginUserInfoKey]; CGFloat keyBoradHeight=[value CGRectValue].size.height; float a=self.view4.frame.origin.y+self.view4.frame.size.height; float b = self.view.frame.size.height-a; CGRect viewCGrect=self.view.frame; viewCGrect.origin.y=viewCGrect.origin.y+(keyBoradHeight-b); [self.view setFrame:viewCGrect];}
最後移除通知
-(void)viewWillDisappear:(BOOL)animated{ [super viewWillDisappear:animated]; [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil]; [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];}