实现步骤:
1、注册键盘通知
[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(keyboardWillShow:)name:
UIKeyboardWillShowNotificationobject:nil];
[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(keyboardWillHide:)name:
UIKeyboardWillHideNotificationobject:nil];
2、对应的方法
#pragma mark 键盘出现时调用
- (void)keyboardWillShow:(NSNotification *)aNotification {
//获取键盘的高度
NSDictionary *userInfo = [aNotification userInfo];
NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = [aValue CGRectValue];
keyBoardHeight = keyboardRect.size.height;
//注意下句代码,为了避免键盘第一次出现时,输入框的位置不发生改变
UITextField *textfield = (UITextField *)[self.view viewWithTag:666];
[selftextFieldDidBeginEditing:textfield];
}
3、在 UITextFieldDelegate中重写此方法
#pragma mark 改变输入框的坐标
- (void)textFieldDidBeginEditing:(UITextField *)textField {
[UIViewanimateWithDuration:0.1animations:^{
CGFloat offset = ScreenHeight-(CGRectGetMaxY(textField.frame)+keyBoardHeight+30);
if (offset<=0) {
[UIViewanimateWithDuration:0.3animations:^{
CGRect frame = self.view.frame;
frame.origin.y = offset;
self.view.frame = frame;
}];
}
}];
}
#pragma mark 恢复输入框的位置
- (void)textFieldDidEndEditing:(UITextField *)textField {
[UIViewanimateWithDuration:0.1animations:^{
CGRect frame = self.view.frame;
frame.origin.y = 0;
self.view.frame = frame;
}];
}