菜鸟教程小白 发表于 2022-12-13 14:54:24

ios - 使用Autolayout时在layoutSubviews中添加 subview 是否正确


                                            <p><p>我写了这样的代码,效果很好</p>

<pre><code>@interface SubView()
@property(nonatomic,strong) UIButton* btn;
@end

@implementation SubView


- (void)layoutSubviews
{
    ;
    ;
    self.btn = ;
    self.btn.backgroundColor = ;
    ;
    self.btn.translatesAutoresizingMaskIntoConstraints = NO;
    ;

    NSLayoutConstraint* centerXConstraint = ;
    NSLayoutConstraint* centerYConstraint = ;
    ;
    ;
}
@end
</code></pre>

<p>但在我看来,在使用Autolayout时,系统会分两步做布局<strong>1 Update Pass 2 Layout Pass</strong>,而layoutSubviews在step 2(Layout Pass)中</p >

<p>所以如果我们在 layoutSubviews 中添加 subview ,看起来它会改变 View 的约束,所以我们需要再次进行更新传递和布局传递,所以它会生成一个无限循环..</p>

<p>但事实上,这段代码运行良好,那我哪里错了?</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>请记住,<code>layoutSubviews</code> 将被多次调用。每次删除按钮并重新添加它有什么意义?</p>

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

<p>即使它<em>似乎</em>在工作,你所做的一切在 <code>layoutSubviews</code> 中都没有任何意义。执行此任务一次,然后在其他地方执行。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 使用Autolayout时在layoutSubviews中添加 subview 是否正确,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/42335864/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/42335864/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 使用Autolayout时在layoutSubviews中添加 subview 是否正确