iOS:使用自动布局更改UIScrollview的内容大小

mas*_*gap 9 uiscrollview ios autolayout ios6

我在里面实现一个表单UIScrollView.我打算在键盘打开时在滚动视图内容的底部添加一些空格,以便用户可以看到所有字段.我将表单视图放在UISCrollView使用以下代码添加所有必需的约束内:

 [_infoView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_infoView(1730)]" options:0 metrics:nil views:views]];

[_scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_infoView]|" options:0 metrics:nil views:views]];

[_scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_infoView]|" options:0 metrics:nil views:views]];

[_scrollView addConstraint:[NSLayoutConstraint constraintWithItem:_infoView
                                                        attribute:NSLayoutAttributeCenterX
                                                        relatedBy:NSLayoutRelationEqual
                                                           toItem:_scrollView
                                                        attribute:NSLayoutAttributeCenterX
                                                       multiplier:1
                                                         constant:0]];
Run Code Online (Sandbox Code Playgroud)

如您所见,我在第一行指定了表单的高度,并scrollview自动调整其内容大小.现在我想增加表单的高度,所以我试图用更大的一个重置高度的约束但是它不起作用.然后我尝试使用该[_scrollView setContentSize:]方法,但这也行不通.有人可以帮我吗?

Muh*_*sio -2

我不确定您在哪里添加上面的代码,但下面的代码应该可以解决您的问题

在您的 init 函数中,添加以下内容:

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center addObserver:self selector:@selector(noticeShowKeyboard:) name:UIKeyboardDidShowNotification object:nil];
        [center addObserver:self selector:@selector(noticeHideKeyboard:) name:UIKeyboardWillHideNotification object:nil];
Run Code Online (Sandbox Code Playgroud)

将以下内容添加到您的 .h

CGSize keyboardSize;
int keyboardHidden;      // 0 @ initialization, 1 if shown, 2 if hidden
Run Code Online (Sandbox Code Playgroud)

将以下内容添加到您的 .m

-(void) noticeShowKeyboard:(NSNotification *)inNotification {
    keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    keyboardHidden = 1;
    [self layoutSubviews];        // Not sure if it is called automatically, so I called it


}
-(void) noticeHideKeyboard:(NSNotification *)inNotification {
    keyboardHidden = 2;
    [self layoutSubviews];       // Not sure if it is called automatically, so I called it

}

- (void) layoutSubviews
{
    [super layoutSubviews];

    if(keyboardHidden == 1) {
        scrollview.frame = CGRectMake(scrollview.frame.origin.x, scrollview.frame.origin.y, scrollview.frame.size.width, scrollview.frame.size.height + keyboardSize.height);
    }
    else if(keyboardHidden == 2) {
        scrollview.frame = CGRectMake(scrollview.frame.origin.x, scrollview.frame.origin.y, scrollview.frame.size.width, scrollview.frame.size.height - keyboardSize.height);
    }
}
Run Code Online (Sandbox Code Playgroud)

我覆盖了layoutsubviews,现在我认为它应该有效。