想实现如同聊天界面的输入框随着键盘移动的效果,如图:
轻拍后返回原来的位置:
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapA)];
[self.view addGestureRecognizer:tap];
}
//返回的手势
- (void)tapA{
[self.textField resignFirstResponder];
}
- (void)keyboardWillShow:(NSNotification *)notification {
NSDictionary *userInfo = [notification userInfo];
NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = [aValue CGRectValue];
keyboardRect = [self.textField convertRect:keyboardRect fromView:nil];
// 根据老的 frame 设定新的 frame
CGRect newTextViewFrame = self.textField.frame; // by michael
newTextViewFrame.origin.y = keyboardRect.origin.y - self.textField.frame.size.height;
// 键盘的动画时间,设定与其完全保持一致
NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
NSTimeInterval animationDuration;
[animationDurationValue getValue:&animationDuration];
// 键盘的动画是变速的,设定与其完全保持一致
NSValue *animationCurveObject = [userInfo valueForKey:UIKeyboardAnimationCurveUserInfoKey];
NSUInteger animationCurve;
[animationCurveObject getValue:&animationCurve];
// 开始及执行动画
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:animationDuration];
[UIView setAnimationCurve:(UIViewAnimationCurve)animationCurve];
self.textField.frame = newTextViewFrame;
[UIView commitAnimations];
}
//键盘消失时的处理,文本输入框回到页面底部。
- (void)keyboardWillHide:(NSNotification *)notification {
NSDictionary* userInfo = [notification userInfo];
// 键盘的动画时间,设定与其完全保持一致
NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
NSTimeInterval animationDuration;
[animationDurationValue getValue:&animationDuration];
// 键盘的动画是变速的,设定与其完全保持一致
NSValue *animationCurveObject =[userInfo valueForKey:UIKeyboardAnimationCurveUserInfoKey];
NSUInteger animationCurve;
[animationCurveObject getValue:&animationCurve];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:animationDuration];
[UIView setAnimationCurve:(UIViewAnimationCurve)animationCurve];
CGRect newTextViewFrame = self.textField.frame;
//获取当前屏幕的高度
NSInteger DEVICE_HEIGHT = [UIScreen mainScreen].bounds.size.height;
newTextViewFrame.origin.y = DEVICE_HEIGHT - self.textField.frame.size.height;
self.textField.frame = newTextViewFrame;
[UIView commitAnimations];
}
注意:如果你的输入框是xib中已经加过约束的,输入框不会跟着键盘移动,那么将以上代码中 keyboardWillShow 和 keyboardWillHide 方法 中的所有的 self.textField 改为 self.view 就可以啦。然后不是xib拖拽的,代码添加的输入框,也可能不是想要的结果,就用同样的处理方法