在自动布局中,scrollview setContentOffset无法正常工作

时间:2015-05-19 09:19:25

标签: ios objective-c uitextfield autolayout

我正在使用全自动布局。

上次UITextField(完成前的视图结束按钮):我在setContentOffset中设置了textFieldDidBeginEditing,它工作正常,但是当我尝试滚动时(在显示的键盘上),{{ 1}}恢复正常。

然后将文本字段返回键盘。我的代码位于UIScrollView

我正在使用textFieldDidBeginEditing用于下一个和上一个和完成按钮。

bskeyboardcontroller

1 个答案:

答案 0 :(得分:1)

问题是您在View中的KeyBoard外观上的滚动视图高度,只需更改滚动昆虫或框架以避免此问题,如果滚动视图内容偏移大于(内容大小 - 滚动视图框架大小),滚动它将自动重置滚动视图。

试试这段代码:

  - (void)viewWillAppear:(BOOL)animated {

        [super viewWillAppear:animated];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardWillHideNotification object:nil];
    }

    - (void)viewWillDisappear:(BOOL)animated {

        [super viewWillDisappear:animated];
        [[NSNotificationCenter defaultCenter] removeObserver:self];

    }

    - (void)keyboardDidShow:(NSNotification *)notification {

        CGRect keyboardRect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
        keyboardRect = [self.view convertRect:keyboardRect fromView:nil];

        UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardRect.size.height, 0.0);
        scrollView.contentInset = contentInsets;
        scrollView.scrollIndicatorInsets = contentInsets;

CGRect aRect = self.view.frame;
    aRect.size.height -= keyboardRect.size.height;
    if (!CGRectContainsPoint(aRect, currentTextField.frame.origin) ) {
        [scrollView scrollRectToVisible:currentTextField.frame animated:NO];
    }
    }
    - (void)keyboardDidHide:(NSNotification *)notification
    {

        UIEdgeInsets contentInsets = UIEdgeInsetsZero;
        scrollView.contentInset = contentInsets;
        scrollView.scrollIndicatorInsets = contentInsets;
    }