我写了这样的代码,它们很好用
@interface SubView()
@property(nonatomic,strong) UIButton* btn;
@end
@implementation SubView
- (void)layoutSubviews
{
[super layoutSubviews];
[self.btn removeFromSuperview];
self.btn = [UIButton buttonWithType:UIButtonTypeCustom];
self.btn.backgroundColor = [UIColor greenColor];
[self.btn setTitle:@"btn" forState:UIControlStateNormal];
self.btn.translatesAutoresizingMaskIntoConstraints = NO;
[self addSubview:self.btn];
NSLayoutConstraint* centerXConstraint = [self.btn.centerXAnchor constraintEqualToAnchor:self.centerXAnchor];
NSLayoutConstraint* centerYConstraint = [self.btn.centerYAnchor constraintEqualToAnchor:self.centerYAnchor];
[self addConstraint:centerXConstraint];
[self addConstraint:centerYConstraint];
}
@end
但是在我看来,当使用Autolayout时,系统会分两步进行布局1 更新Pass 2 布局Pass,而layoutSubviews在第二步(布局Pass)中。
因此,如果我们在layoutSubviews中添加子视图,似乎会更改视图的约束条件,因此我们需要再次进行更新和布局Pass,这将导致无限循环...
但事实上,这段代码运行良好,那么我错在哪里了?
subView
不会改变视图的约束条件,因此不会调用layoutSubviews
。然而,在layoutSubviews
中添加子视图并不是一个好的做法,最好在初始化器中完成。 - Eric QianlayouSubiviews
会被调用,或者如果您执行setNeedsLayout
或layoutIfNeeded
手动触发布局。 - Eric Qian