12

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

当键盘出现时我使用这个代码:

- (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];
    }];
}
4

2 回答 2

31

尝试不考虑内容大小,而是调整滚动视图的 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;
}
于 2013-11-01T23:11:52.630 回答
3

我发现最好的方法是像这样覆盖 NSLayoutConstraint:

@implementation NHKeyboardLayoutConstraint

- (void) dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void) awakeFromNib {
    [super awakeFromNib];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillChangeFrame:)
                                                 name:UIKeyboardWillChangeFrameNotification
                                               object:nil];
}

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

    CGRect endKBRect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];

    CGFloat animationDuration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    CGRect frame = [UIApplication sharedApplication].keyWindow.bounds;

    self.constant = frame.size.height - endKBRect.origin.y;


    [UIView animateWithDuration:animationDuration animations:^{
        [[UIApplication sharedApplication].keyWindow layoutIfNeeded];
    }];
}


@end

然后在您的 xib 中将违规约束的类类型更改为此类。

于 2015-08-03T13:39:08.777 回答