1.平移整個界面(不推薦)
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
// 獲得textField座標和View的中間比較
CGFloat height = self.labelTextViewAccount.center.y - self.view.frame.size.height / 2.0;
// 如果大於0,說明鍵盤遮住了控件,就將整個界面向上平移
if(height > 0){
self.view.center = CGPointMake(self.view.center.x, self.view.center.y - height);
}
return YES;
}
2.使用動畫的方式移動控件(推薦)
//
self.view.backgroundColor = [UIColor cyanColor];
self.myView = [[UIView alloc] initWithFrame:CGRectMake(100, 600, 200, 50)];
self.myView.backgroundColor = [UIColor yellowColor];
[self.view addSubview:self.myView];
self.textField= [[UITextField alloc] initWithFrame:CGRectMake(100, 100, 150, 50)];
self.textField.backgroundColor = [UIColor yellowColor];
[self.view addSubview:self.textField];
// 監聽鍵盤的彈起和回收
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillAppear:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillDiapper:) name:UIKeyboardWillHideNotification object:nil];
// 實現彈起和收縮方法
// 鍵盤彈起的時候觸發的方法
- (void)keyBoardWillAppear:(NSNotification *)notification{
NSLog(@"鍵盤彈起了");
// 找到鍵盤的尺寸
CGRect rect = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
// 整體打印結構體的方法
NSLog(@"%@",NSStringFromCGRect(rect));
// 用UIView的動畫,讓視圖隨鍵盤上移
[UIView animateWithDuration:0.2 animations:^{
self.myView.frame = CGRectMake(100, 600 - rect.size.height, 200, 50);
}];
}
// 點擊空白處,回收鍵盤
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[super touchesBegan:touches withEvent:event];
[self.textField resignFirstResponder];
}
// 鍵盤迴收的時候觸發的方法
- (void)keyBoardWillDiapper:(NSNotification *)notification{
NSLog(@"鍵盤迴收了");
// 通過UIView動畫,讓視圖回收
[UIView animateWithDuration:0.2 animations:^{
self.myView.frame = CGRectMake(100, 600, 200, 50);
}];
}