我有一些代码以编程方式创建自动布局约束,并将它们添加到 View 中。
有两种方法可以做到这一点 - 在 superView 上调用 addConstraints
,或者在每个约束上设置 .isActive = true
(在内部调用 addConstraint)
选项 1:
parent.addConstraints([
child.topAnchor.constraint(equalTo: parent.topAnchor, constant: 20),
child.leftAnchor.constraint(equalTo: parent.leftAnchor, constant: 5) ])
选项 2:
child.topAnchor.constraint(equalTo: parent.topAnchor, constant: 20).isActive = true
child.leftAnchor.constraint(equalTo: parent.leftAnchor, constant: 5).isActive = true
我的问题是,做一个比做另一个有什么好处吗? (性能/等)还是纯粹归结为风格。
(我认为在下一次布局传递之前不会评估约束,所以我认为我们逐个添加它们而不是在一个 block 中添加它们应该无关紧要??)
如果只是风格,社区“更喜欢”的风格是什么?
(我个人更喜欢 addConstraints,但它非常接近,我很容易被 .isActive 左右)
最佳答案
根据关于addConstraint:
的文档,建议为个别约束 设置active
属性。 (注意:active
属性仅适用于 iOS 8+)。
When developing for iOS 8.0 or later, set the constraint’s active property to YES instead of calling the addConstraint: method directly. The active property automatically adds and removes the constraint from the correct view. (reference)
此外,如果您查看 addConstraint:
的接口(interface)定义,它有这样的注释:
// This method will be deprecated in a future release and should be avoided. Instead, set NSLayoutConstraint's active property to YES
话虽这么说,实际上还有第三种 [可能更好] 的选择,即使用 NSLayoutConstraint
的类方法 activate:
:
NSLayoutConstraint.activate([
child.topAnchor.constraint(equalTo: parent.topAnchor, constant: 20),
child.leftAnchor.constraint(equalTo: parent.leftAnchor, constant: 5) ])
根据文档和接口(interface)文件,这也是推荐的方案。因此,如果您有多个约束,这将是一个简单的解决方案,并且可能更适合您的情况。
(界面评论;强调我的):
Convenience method that activates each constraint in the contained array, in the same manner as setting active=YES. This is often more efficient than activating each constraint individually.
关于iOS 约束样式 : addConstraints vs . isActive = true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39938900/