当键盘被隐藏时,scrollview应该返回到它的原始contentInset,但它在iOS7中不起作用。设置scrollview的contentInset时显示键盘工作但键盘隐藏时,scrollview的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;
}
答案 0 :(得分:9)
试试这个:
self.automaticallyAdjustsScrollViewInsets = NO;
这对我有用......
答案 1 :(得分:1)
它可能与contentSize不起作用有关 除了在VC中设置
- (void)viewDidLayoutSubviews
{
self.scrollView.contentSize = whatever
}
只是说你可能会把头撞到错误的墙上
答案 2 :(得分:0)
所以,仅仅因为我仍然觉得这个答案很有用,这就是我所做的。我接受了@ alex-i的建议和@ yong-ho的评论。但由于某种原因,导航栏的高度还不够。
UIEdgeInsets contentInsets = UIEdgeInsetsMake(self.navigationController.navigationBar.frame.size.height + 20.0f, 0.0, 0.0, 0.0);
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
就像我说的,我必须添加20.0f或我的内容仍然被切断。不知道为什么。如果我弄清楚,我会更新我的答案。
答案 3 :(得分:0)
将contentOffset设置为零。无论您的滚动视图位于导航控制器内还是其他任何位置,它都适用于所有情况。在下面找到相同的代码段:
- (void)keyboardWasHidden:(NSNotification *)notif
{
UIScrollView *scrollView = (UIScrollView *)self.view;
scrollView.contentOffset = CGPoint.zero
}
答案 4 :(得分:0)
我还发现,如果将新的contentinset设置为与现有inset完全相同,则滚动视图可能会忽略它并将其恢复为零inset。因此,一种简单的解决方法是检查您要设置的新contentinset与上一个至少有1分不同。