当键盘被隐藏时,滚动视图应该回到它的原始 contentInset,但它在 iOS7 中不起作用。在显示键盘时设置滚动视图的 contentInset 是有效的,但是当键盘被隐藏时,滚动视图的 contentInset 不能设置为零。编码:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:Nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardDidHideNotification object:nil];
}
- (void)keyboardWasShown:(NSNotification *)notif
{
CGSize keyboardSize = [[[notif userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0, 0, keyboardSize.height, 0);
UIScrollView *scrollView = (UIScrollView *)self.view;
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
CGRect rect = self.view.frame;
rect.size.height -= keyboardSize.height;
if (!CGRectContainsPoint(rect, self.wishContentField.frame.origin)) {
CGPoint point = CGPointMake(0, self.wishContentField.frame.origin.y - keyboardSize.height);
[scrollView setContentOffset:point animated:YES];
}
}
- (void)keyboardWasHidden:(NSNotification *)notif
{
UIEdgeInsets zeroInsets = UIEdgeInsetsZero;
UIScrollView *scrollView = (UIScrollView *)self.view;
[scrollView setContentInset:zeroInsets];
scrollView.scrollIndicatorInsets = zeroInsets;
}