我正在制作一个根据约束自动调整大小的自定义选项卡 View ,当我尝试向其中添加也使用约束的 subview 时遇到问题。
如果我添加一个 subview 并给予它约束,例如这样:
- (void)awakeFromNib {
[super awakeFromNib];
UIBlurEffect* blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
background = [[UIVisualEffectView alloc] initWithEffect:blur];
NSLayoutConstraint* topConstraint = [NSLayoutConstraint constraintWithItem:background
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeTop
multiplier:1
constant:0];
NSLayoutConstraint* leadConstraint = [NSLayoutConstraint constraintWithItem:background
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeLeading
multiplier:1
constant:0];
NSLayoutConstraint* trailConstraint = [NSLayoutConstraint constraintWithItem:background
attribute:NSLayoutAttributeTrailing
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeTrailing
multiplier:1
constant:0];
NSLayoutConstraint* botConstraint = [NSLayoutConstraint constraintWithItem:background
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeBottom
multiplier:1
constant:0];
[background setFrame:self.bounds];
[self addSubview:background];
[self addConstraints:@[topConstraint, leadConstraint, trailConstraint, botConstraint]];
}
选项卡 View 将不再响应约束。如果我将选项卡 View 添加到 Storyboard并尝试对其设置约束,它只是不响应。我可以手动调整它的大小以使其适合约束,但它不会自动执行此操作,并且更改设备当然会打破约束。
删除添加约束的这一行可以解决问题,但我希望 subview 根据约束自动调整大小。
//[self addConstraints:@[topConstraint, leadConstraint, trailConstraint, botConstraint]];
这可能吗,还是我只需要在调用布局更新时使 View 调整其所有 subview 的大小?
最佳答案
正如@DonMag所说,background.translatesAutoresizingMaskIntoConstraints = NO;也许是正确的答案。
或者您可以尝试删除 addConstraints,并使用 topConstraint.active = YES 等。
关于ios - subview 约束打破父 View 约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57499498/