带有滚动视图和键盘的iOS AutoLayout

Bar*_*cki 11 uiscrollview ios autolayout

我在故事板上有一个视图来显示用户登录表单,所以它看起来像这样:主视图 - >滚动视图 - >内容视图 - >顶部的两个文本字段和登录按钮以及底部的一个注册按钮风景.我使用自动布局,底部按钮有底部空间约束.当我点击文本字段并出现键盘时,我想滚动视图以将大小更改为可见的rect,但内容大小应保持向下滚动到注册按钮,但当滚动视图的大小更改时按钮会向上移动.我怎么能做我想要的?

键盘出现时我使用此代码:

- (void)keyboardWillShow:(NSNotification *)aNotification
{
    NSDictionary *info = [aNotification userInfo];
    NSValue *kbFrame = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    NSTimeInterval animationDuration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect keyboardFrame = [kbFrame CGRectValue];

    CGSize s = self.scrollView.contentSize;
    CGFloat height = keyboardFrame.size.height;
    self.scrollViewBottomLayoutConstraint.constant = height;

    [UIView animateWithDuration:animationDuration animations:^{
        [self.view layoutIfNeeded];
        [self.scrollView setContentSize:s];
    }];
}
Run Code Online (Sandbox Code Playgroud)

bil*_*tum 30

尝试单独保留内容大小,而是调整滚动视图的contentInset属性.然后你不必乱用约束.

- (void)keyboardUp:(NSNotification *)notification
{
    NSDictionary *info = [notification userInfo];
    CGRect keyboardRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];

    UIEdgeInsets contentInset = self.scrollView.contentInset;
    contentInset.bottom = keyboardRect.size.height;
    self.scrollView.contentInset = contentInset;
}
Run Code Online (Sandbox Code Playgroud)