我正在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]];
如您所见,我在第一行指定了表单的高度,scrollview
自动调整其内容大小。现在我想增加表单的高度,所以我试图用更大的一个重置高度的约束但是它不起作用。然后我尝试使用[_scrollView setContentSize:]
方法,但这也行不通。有人可以帮帮我吗?
答案 0 :(得分:4)
如果我理解了这个问题,我建议您调整contentInset
上的UIScrollView
属性,而不是调用layoutSubviews
。请注意,文档说:
使用此属性可添加到内容周围的滚动区域。单位是点。默认值为
UIEdgeInsetsZero
。
您仍然需要侦听键盘隐藏/显示通知,以便知道何时调整滚动视图的高度:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
然后在keyboardWillShow
中你可以这样做:
UIEdgeInsets insets = UIEdgeInsetsMake(0, 0, 100, 0);
scrollView.contentInset = insets;
100
是您要调整scrollView
的高度。我使用UITableView
执行此操作,其中我将表单元素设置为UITableViewCell
,并且效果很好。
答案 1 :(得分:-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];
将以下内容添加到.h
CGSize keyboardSize;
int keyboardHidden; // 0 @ initialization, 1 if shown, 2 if hidden
将以下内容添加到.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);
}
}
我压倒layoutsubviews
,现在我认为它应该有效。