如若在一个列表中,每个cell中都有一个编辑框,当处于编辑状态时,会弹出软键盘,需要通过计算软键盘的高度来移动整个列表的位置。
下面这个方法是,获取当前编辑框的坐标
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
CGPoint eventPoint = [textField convertPoint:textField.frame.origin toView:appDelegate.window];
_viewMoveHeight = eventPoint.y;
return YES;
}
监听软键盘事件
//软键盘
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardAction:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardAction:)
name:UIKeyboardWillHideNotification
object:nil];
事件实现
- (void)keyboardAction:(NSNotification *)notification
{
NSDictionary *userInfo = [notification userInfo];
NSValue *animationDuration = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
NSTimeInterval timeInt;
[animationDuration getValue:&timeInt];
NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = [aValue CGRectValue];
CGFloat keyBoradHeight = keyboardRect.size.height;
if (keyBoradHeight <= 0) {
return;
}
CGFloat offestY = kScreen_H - keyBoradHeight;
CGFloat paading = 10;
__block CGFloat moveY;
if (_curTouchPointHeight > offestY) {
moveY = _curTouchPointHeight - offestY + paading;
}else{
moveY = 0;
}
if (notification.name == UIKeyboardWillShowNotification) {
if (isShowKeyboard == NO) {
[UIView animateWithDuration:timeInt
delay:0.f
options:UIViewAnimationOptionCurveEaseOut
animations:^{
CGRect oldFrame = self.tableView.frame;
oldFrame.origin.y -= moveY;
self.tableView.frame = oldFrame;
} completion:^(BOOL finished) {
isShowKeyboard = YES;
}];
_tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyBoardHiden:)];
[self.view addGestureRecognizer:_tap];
}
} else if (notification.name == UIKeyboardWillHideNotification) {
[UIView animateWithDuration:-timeInt
delay:0.f
options:UIViewAnimationOptionCurveEaseOut
animations:^{
CGRect oldFrame = self.tableView.frame;
oldFrame.origin.y = 0;
self.tableView.frame = oldFrame;
} completion:^(BOOL finished) {
isShowKeyboard = NO;
}];
}
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}