我以编程方式创建约束,以便视图控制器视图具有背景视图和工具栏,工具栏位于底部。我希望背景视图的高度随着工具栏高度的增加而减小。将背景视图和工具栏作为子视图添加到视图控制器的视图后,我调用(在viewDidLoad中)以编程方式设置约束的方法。
- (void)configureConstraintsForBackgroundViewAndToolbar {
[self.backgroundView setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.toolbarComponent setTranslatesAutoresizingMaskIntoConstraints:NO];
UIView *constraintsBackgroundView = self.backgroundView;
UIView *constraintsToolbar = self.toolbarComponent;
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(
constraintsBackgroundView,
constraintsToolbar);
NSDictionary *metricsDictionary = @{
@"toolbarHeight":[NSNumber numberWithFloat:TOOLBAR_HEIGHT]
};
[NSLayoutConstraint activateConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(0)-[constraintsBackgroundView]-(0)-|"
options:NSLayoutFormatDirectionLeadingToTrailing
metrics:metricsDictionary
views:viewsDictionary]];
[NSLayoutConstraint activateConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(0)-[constraintsToolbar]-(0)-|"
options:NSLayoutFormatDirectionLeadingToTrailing
metrics:metricsDictionary
views:viewsDictionary]];
[NSLayoutConstraint activateConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(0)-[constraintsBackgroundView]-(0)-[constraintsToolbar(>=toolbarHeight)]-(0)-|"
options:NSLayoutFormatDirectionLeadingToTrailing
metrics:metricsDictionary
views:viewsDictionary]];
}
这一点工作正常,直到我尝试使用以下方法更新工具栏的高度(通过嵌入的文本视图)。我在这里做错了吗?工具栏高度增加但背景视图的高度没有缩短(我使用SparkInspector调试)。看起来相当简单,我在这里遗漏了一些明显的东西......
- (void)textViewDidChange:(UITextView *)textView {
if (textView != self.toolbarTextView) {
return;
}
CGFloat currentHeight = self.bounds.size.height;
CGSize size = [textView sizeThatFits:CGSizeMake(textView.frame.size.width, textView.frame.size.height)];
CGFloat determinedHeight = fminf(fmaxf(size.height, TOOLBAR_HEIGHT), MAX_TOOLBAR_HEIGHT);
[self setBounds:CGRectMake(0, 0, self.bounds.size.width, determinedHeight)];
[self setNeedsLayout];
}
另外,如果我查询工具栏和背景视图的约束,我最初设置的彼此之间的约束不会出现?它们只显示视图控制器的视图......这对我来说听起来不正确......?
非常感谢......
答案 0 :(得分:1)
如果使用约束设置布局,则为视图设置边界或框架以更新布局没有意义。而是通过更改约束的constant
属性
例如:
使用特定约束设置工具栏的高度并将其存储在属性
中NSLayoutConstraint *toolBarHeightConstraint = [NSLayoutConstraint constraintWithItem:constraintsToolbar
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1
constant:TOOLBAR_HEIGHT];
然后通过更改约束的常量来更改工具栏的高度。 像:
toolBarHeightConstraint.constant = newHeight;
在您的情况下,您还需要将垂直约束更改为:
[NSLayoutConstraint activateConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(0)-[constraintsBackgroundView]-(0)-[constraintsToolbar]-(0)-|"
options:NSLayoutFormatDirectionLeadingToTrailing
metrics:metricsDictionary
views:viewsDictionary]];
有关详细信息,请查看this答案。