点击文本框调用通知中心实现键盘的显示与关闭:
//键盘事件监听
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(changeContentViewPosition:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(changeContentViewPosition:)
name:UIKeyboardWillHideNotification
object:nil];
//view随着键盘变化高度
- (void) changeContentViewPosition:(NSNotification *)notification{
NSDictionary *userInfo = [notification userInfo];
NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGFloat keyBoardEndY = value.CGRectValue.origin.y;
NSNumber *duration = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
NSNumber *curve = [userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
[UIView animateWithDuration:duration.doubleValue animations:^{
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationCurve:[curve intValue]];
self.view.center = CGPointMake(self.view.center.x, keyBoardEndY-self.view.bounds.size.height/2.0);
}];
}
//点击屏幕键盘退出
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
}