【发布时间】:2019-01-14 03:35:13
【问题描述】:
我的应用程序中有以下层次结构
- UIScrollView
- UIStackView
- UIView 1 // load with xib and added in arrangedSubviews
- UIScrollView 1.1 // horizontal scrolling, fixed height constraint 38
- UIView 1.2 // called it childView. has fixed height 0 (I load the view from xib and add it here dynamically and update its height)
- UIView 1.2.1 // called it New View
- UIView 2
- UIView 3
所以我的问题是,当我从 xib 加载视图并将其添加到 UIView1.2 时,还将高度约束 0 增加到新添加的子视图的高度,但不会发生任何事情。UIView1.2height 没有按预期更新。
self.constraintChildViewHeight.constant = 95;
[self layoutIfNeeded];
NewView *newView = (NewView *)[[[NSBundle mainBundle]loadNibNamed:NSStringFromClass([FieldPhotoView class]) owner:self options:nil]objectAtIndex:0];
[newView setTranslatesAutoresizingMaskIntoConstraints:false];
[self.childView addSubview:newView];
[self applyConstraintsToParent:self.childView andSubView:newView];
方法
- (void)applyConstraintsToParent:(UIView *)parentView andSubView:(UIView *)subView {
//constraints
NSLayoutConstraint *leading = [NSLayoutConstraint constraintWithItem:subView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:parentView attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0];
[parentView addConstraint:leading];
NSLayoutConstraint *trailing = [NSLayoutConstraint constraintWithItem:subView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:parentView attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:0];
[parentView addConstraint:trailing];
NSLayoutConstraint *top = [NSLayoutConstraint constraintWithItem:subView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:parentView attribute:NSLayoutAttributeTop multiplier:1.0 constant:0];
[parentView addConstraint:top];
NSLayoutConstraint *bottom = [NSLayoutConstraint constraintWithItem:subView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:parentView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-8];
[parentView addConstraint:bottom];
NSLayoutConstraint *equalWidth = [NSLayoutConstraint constraintWithItem:subView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:parentView attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0];
[parentView addConstraint:equalWidth];
leading.active = true;
trailing.active = true;
top.active = true;
bottom.active = true;
equalWidth.active = true;
}
#Edit1 - 子视图约束
#Edit2 - 为了更好地理解,我想使用 xib 以编程方式实现此功能(在 UIStoryBoard 中工作正常。)
【问题讨论】:
-
仍然没有提到所有的约束。你有连接子视图和它的超级视图的底部约束吗?您的代码中的
self是什么? (现在可以说你绝对不需要equalWidth约束,因为根据前导和尾随约束,宽度已经必须相等) -
好的,我将放置另一个图像作为子视图约束,self 是添加到 UIStackView 的 UIView 1。你能看看我的视图层次结构吗?
-
@AntonFilimonov 请查看我更新的问题。
-
试图做同样的事情 - 一切都按预期工作。你在控制台中收到任何警告吗?可能有些约束存在冲突。
-
不,没有一个警告。但在我的情况下它不起作用。
标签: ios objective-c uiscrollview uistackview