【发布时间】:2017-02-20 03:11:32
【问题描述】:
我写了这样的代码,效果很好
@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 Update Pass 2 Layout Pass,layoutSubviews在step 2(Layout Pass)中
所以如果我们在 layoutSubviews 中添加子视图,似乎它会改变视图的约束,所以我们需要再次进行更新传递和布局传递,所以它会生成一个无限循环..
但事实上,这段代码运行良好,那我哪里错了?
【问题讨论】:
-
添加
subView不会改变视图的约束,因此layoutSubviews不会被调用。但是layoutSubviews不是添加子视图的好地方,最好在初始化器中添加。 -
你的意思是上面的 centerXConstraint 不是视图的约束,而是子视图的约束?所以视图的 layoutSubviews 可以正确布局
-
是的,它只是将按钮与视图的 centerX 对齐,这不会影响视图本身的位置/大小。
layouSubiviews会在视图的框架更改时调用,或者如果您使用setNeedsLayout或layoutIfNeeded手动触发布局。 -
好的,知道了,非常感谢@EricQian
标签: ios objective-c autolayout