9

当键盘被隐藏时,滚动视图应该回到它的原始 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;
}
4

5 回答 5

10

试试这个:

self.automaticallyAdjustsScrollViewInsets = NO;

这对我有用...

于 2013-11-25T14:26:12.050 回答
1

它可能与 contentSize 不工作有关,除非在 VC 中设置

- (void)viewDidLayoutSubviews
{
     self.scrollView.contentSize = whatever
}

只是说你可能把头撞错了墙

于 2014-09-23T07:38:59.483 回答
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 否则我的内容仍然被切断。不知道为什么。如果我弄清楚了,我会更新我的答案。

于 2014-06-19T07:13:18.520 回答
0

将 contentOffset 设置为零。无论您的滚动视图是在导航控制器内还是其他任何情况下,它都适用。在下面的代码片段中找到相同的:

- (void)keyboardWasHidden:(NSNotification *)notif
{    
    UIScrollView *scrollView = (UIScrollView *)self.view;
    scrollView.contentOffset = CGPoint.zero
}
于 2018-05-29T14:12:14.227 回答
0

我还发现,如果您将新的 contentinset 设置为与现有插图完全相同,则滚动视图可能会忽略它并恢复为零插图。因此,一个简单的解决方法是检查您设置的新 contentinset 是否与上一个至少相差 1 点。

于 2020-05-31T06:07:03.707 回答