我正在制作一个自定义选项卡视图,该视图会根据约束条件自动调整大小,当我尝试向其添加也使用约束条件的子视图时遇到问题。
如果我添加一个子视图并赋予它约束,例如:
- (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]];
}
选项卡视图将不再响应约束。如果我将选项卡视图添加到情节提要中并尝试在其上设置约束,则它不会响应。我可以手动调整它的大小以使其符合约束,但是它不会自动执行,更改设备当然会打破约束。
删除此行以添加约束可解决此问题,但我希望子视图根据约束自动调整大小。
//[self addConstraints:@[topConstraint, leadConstraint, trailConstraint, botConstraint]];
这是可能的,还是在调用布局更新时仅使视图重新调整其所有子视图的大小?
答案 0 :(得分:0)
正如@DonMag所说,background.translatesAutoresizingMaskIntoConstraints = NO;也许是正确答案。
或者您可以尝试删除addConstraints,并使用topConstraint.active = YES,等等。