OGeek|极客世界-中国程序员成长平台

标题: ios - 使用Autolayout时在layoutSubviews中添加 subview 是否正确 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 14:54
标题: ios - 使用Autolayout时在layoutSubviews中添加 subview 是否正确

我写了这样的代码,效果很好

@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 ,看起来它会改变 View 的约束,所以我们需要再次进行更新传递和布局传递,所以它会生成一个无限循环..

但事实上,这段代码运行良好,那我哪里错了?



Best Answer-推荐答案


请记住,layoutSubviews 将被多次调用。每次删除按钮并重新添加它有什么意义?

另外,layoutSubviews 是自动布局系统遵循约束的地方。那么在 layoutSubviews 中设置按钮的约束有什么意义呢?

即使它似乎在工作,你所做的一切在 layoutSubviews 中都没有任何意义。执行此任务一次,然后在其他地方执行。

关于ios - 使用Autolayout时在layoutSubviews中添加 subview 是否正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42335864/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4