【发布时间】:2013-10-04 14:45:12
【问题描述】:
当键盘被隐藏时,滚动视图应该回到它的原始 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;
}
【问题讨论】:
-
你能解释一下它是如何不工作的(键盘隐藏后它是如何工作的)吗?请注意,在 iOS 7 上,如果您有一个半透明的
navigationBar,您的视图控制器将在您的滚动视图中设置一个顶部插图(如果没有另外设置)。这里可能就是这种情况,因为你设置的是contentInset.top=0,所以它可能会隐藏navigationBar或statusBar后面的一些内容。 -
感谢您的回复。我将顶部设置为 navigationBar.frame.size.height,它现在可以工作了。
-
写一个答案并给 alex-i 一些信任 ;)
标签: ios uiscrollview ios7