gpt4 book ai didi

ios - 以编程方式创建 View 时,我应该在哪里设置自动布局约束

转载 作者:IT王子 更新时间:2023-10-29 07:31:22 26 4
gpt4 key购买 nike

我看到了设置约束的不同示例。一些在 viewDidLoad/loadView 中设置它们(在添加 subview 之后)。其他人在 updateViewConstraints 方法中设置它们,该方法由 viewDidAppear 调用。

当我尝试在 updateViewContraints 中设置约束时,布局可能会跳动,例如在 View 出现之前稍有延迟。此外,如果我使用此方法,我是否应该先清除现有约束,即 [self.view [removeConstraints:self.view.constraints]

最佳答案

我在 viewDidLoad/loadView 中设置了我的约束(我的目标是 iOS >= 6)。 updateViewConstraints 对于更改约束值很有用,例如如果某些约束取决于屏幕的方向(我知道,这是一种不好的做法),您可以在此方法中更改其 constant

viewDidLoad 中添加约束显示在 “iOS 和 OS X 自动布局简介”(WWDC 2012) session 期间,从 39:22 开始。我认为这是在讲座中说过但没有出现在文档中的事情之一。

更新:我注意到在 Resource Management in View Controllers 中提到了设置约束。 :

If you prefer to create views programmatically, instead of using a storyboard, you do so by overriding your view controller’s loadView method. Your implementation of this method should do the following:

(...)

3.If you are using auto layout, assign sufficient constraints to each of the views you just created to control the position and size of your views. Otherwise, implement the viewWillLayoutSubviews and viewDidLayoutSubviews methods to adjust the frames of the subviews in the view hierarchy. See “Resizing the View Controller’s Views.”

更新 2:WWDC 2015 期间 Apple gave a new explanation updateConstraintsupdateViewConstraints 推荐用法:

Really, all this is is a way for views to have a chance to make changes to constraints just in time for the next layout pass, but it's often not actually needed.

All of your initial constraint setup should ideally happen inside Interface Builder.

Or if you really find that you need to allocate your constraints programmatically, some place like viewDidLoad is much better.

Update constraints is really just for work that needs to be repeated periodically.

Also, it's pretty straightforward to just change constraints when you find the need to do that; whereas, if you take that logic apart from the other code that's related to it and you move it into a separate method that gets executed at a later time, your code becomes a lot harder to follow, so it will be harder for you to maintain, it will be a lot harder for other people to understand.

So when would you need to use update constraints?

Well, it boils down to performance.

If you find that just changing your constraints in place is too slow, then update constraints might be able to help you out.

It turns out that changing a constraint inside update constraints is actually faster than changing a constraint at other times.

The reason for that is because the engine is able to treat all the constraint changes that happen in this pass as a batch.

关于ios - 以编程方式创建 View 时,我应该在哪里设置自动布局约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19387998/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com