- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardDidShow:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardDidHide:) name:UIKeyboardDidHideNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];
}
- (void)keyBoardDidShow:(NSNotification *)notif {
NSLog(@"===键盘显示====");
if (keyboardDidShow) return;
//获取键盘大小
NSDictionary *info = [notif userInfo];
NSValue *aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;
//注意:系统键盘有两个不同的高度(216和258),为了保持正常显示,键盘高度取258
if (keyboardSize.height == 216) {
keyboardSize.height = 258;
}else{
keyboardSize.height = 258;
}
//重置scrollview的frame
CGRect viewFrame = self.scrollView.frame;
viewFrame.size.height -= keyboardSize.height+44;
self.scrollView.frame = viewFrame;
//滚动到当前控件
CGRect textfieldRect = [self.nameTextField frame];
[self.scrollView scrollRectToVisible:textfieldRect animated:YES];
keyboardDidShow = YES;
}
- (void)keyBoardDidHide:(NSNotification *)notif {
NSLog(@"====键盘隐藏====");
NSDictionary *info = [notif userInfo];
NSValue *aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;
CGRect viewFrame = self.scrollView.frame;
viewFrame.size.height += keyboardSize.height+44;
self.scrollView.frame = viewFrame;
if (!keyboardDidShow) {
return;
}
keyboardDidShow = NO;
}
网友评论