在做聊天或某些特定界面的时候,需要触发textField的键盘。而部分界面会被遮挡住。本文提供了一个很好的解决方法。
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didClickKeyboard:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didKboardDisappear:) name:UIKeyboardWillHideNotification object:nil];
}
#pragma mark - 键盘即将跳出
-(void)didClickKeyboard:(NSNotification *)sender{
CGFloat durition = [sender.userInfo[@"UIKeyboardAnimationDurationUserInfoKey"] doubleValue];
CGRect keyboardRect = [sender.userInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
CGFloat keyboardHeight = keyboardRect.size.height;
[UIView animateWithDuration:durition animations:^{
self.view.transform = CGAffineTransformMakeTranslation(0, -keyboardHeight);
}];
}
#pragma mark - 当键盘即将消失
-(void)didKboardDisappear:(NSNotification *)sender{
CGFloat duration = [sender.userInfo[@"UIKeyboardAnimationDurationUserInfoKey"] doubleValue];
[UIView animateWithDuration:duration animations:^{
self.view.transform = CGAffineTransformIdentity;
}];
}
其中打印一下观察者的userInfo 属性可以获取到:
UIKeyboardAnimationCurveUserInfoKey = 7;
UIKeyboardAnimationDurationUserInfoKey = "0.25";
UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {320, 253}}";
UIKeyboardCenterBeginUserInfoKey = "NSPoint: {160, 353.5}";
UIKeyboardCenterEndUserInfoKey = "NSPoint: {160, 606.5}";
UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 227}, {320, 253}}";
UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 480}, {320, 253}}";
UIKeyboardIsLocalUserInfoKey = 1;
添加上键盘消失的代码,测试一下。希望对大家有用。
网友评论