1 //設置輸入框 ---《由於輸入框用了get方法,因此第一次調用輸入框要用self 調用》;
2 self.textlab.frame=CGRectMake(20, 420, 250, 30); 3 _textlab.layer.borderColor=[UIColor blueColor].CGColor; 4 _textlab.layer.borderWidth= 0.5f; 5 _textlab.backgroundColor=[UIColor colorWithRed:0.830 green:0.801 blue:0.881 alpha:1.000]; 6
7 //添加輸入框到視圖
8 [self.view addSubview:self.textlab]; 9
10 //監聽鍵盤,鍵盤出現
11 [[NSNotificationCenter defaultCenter]addObserver:self
selector:@selector(keyboardwill:)
name:UIKeyboardWillShowNotification object:nil]; 12
13 //監聽鍵盤隱藏
14 [[NSNotificationCenter defaultCenter]addObserver:self
selector:@selector(keybaordhide:)
name:UIKeyboardWillHideNotification object:nil]; 15
16 //設置點擊手勢,當點擊空白處,結束編輯,收回鍵盤
17 UITapGestureRecognizer *tapp=[[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(tapAction:)]; 18 //開啓交互
19 self.view.userInteractionEnabled=YES; 20 //添加手勢到視圖
21 [self.view addGestureRecognizer:tapp];
二、裏面方法的實現app
1 //點擊手勢方法 2 -(void)tapAction:(UITapGestureRecognizer *)sender 3 { 4 [self.view endEditing:YES]; 5 } 6 7 //當鍵盤出現時,調用此方法 8 -(void)keyboardwill:(NSNotification *)sender 9 { 10 //獲取鍵盤高度 11 NSDictionary *dict=[sender userInfo]; 12 NSValue *value=[dict objectForKey:UIKeyboardFrameEndUserInfoKey]; 13 CGRect keyboardrect = [value CGRectValue]; 14 int height=keyboardrect.size.height; 15 16 //若是輸入框的高度低於鍵盤出現後的高度,視圖就上升; 17 if ((_textlab.frame.size.height + _textlab.frame.origin.y)>(self.view.frame.size.height - height)) 18 { 19 self.view.frame = CGRectMake(0, -height, self.view.frame.size.width, self.view.frame.size.height); 20 } 21 } 22 23 //當鍵盤隱藏時候,視圖回到原定 24 -(void)keybaordhide:(NSNotification *)sender 25 { 26 self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height); 27 } 28 29 //輸入框的get方法 30 -(UITextField *)textlab 31 { 32 if (_textlab==nil) 33 { 34 _textlab=[UITextField new]; 35 } 36 return _textlab; 37 }
防止鍵盤遮擋方式二; ide
調用UITextField 輸入框的代理方法 <UITextFieldDelegate>動畫
1 //開始編輯輸入框的時候,軟鍵盤出現,執行此事件 2 -(void)textFieldDidBeginEditing:(UITextField *)textlab 3 { 4 //獲取當前輸入框的位置信息 5 CGRect frame = textlab.frame; 6 //獲取鍵盤底部位置與鍵盤最高點之間的距離,鍵盤高度256 7 int offset = frame.origin.y + frame.size.height - (self.view.frame.size.height - 256.0); 8 //設置視圖上升的時間 9 NSTimeInterval animaTime = 0.30f; 10 //字符串隨意也行... 11 [UIView beginAnimations:@"ResizeForKeyboard" context:nil]; 12 //添加視圖上的上升時間0.3f 13 [UIView setAnimationDuration:animaTime]; 14 15 //將視圖的Y座標向上移動offset個單位,以使下面騰出地方用於軟鍵盤的顯示 16 if(offset > 0) 17 self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height); 18 //提交動畫 19 [UIView commitAnimations]; 20 }
//當用戶按下return鍵或者按回車鍵,keyboard消失 -(BOOL)textFieldShouldReturn:(UITextField *)textField { //收回鍵盤第一響應者意思... [textField resignFirstResponder]; return YES; } //輸入框編輯完成之後,將視圖恢復到原始狀態 -(void)textFieldDidEndEditing:(UITextField *)textField { self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height); }