iOS 约束样式 : addConstraints vs . isActive = true

标签 ios swift autolayout nslayoutconstraint

我有一些代码以编程方式创建自动布局约束,并将它们添加到 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/

相关文章:

ios - 带有自定义 UIButton 的 UIBarButtonItem 在 iOS <= 10 上不可见

ios - 委托(delegate)中的可选返回

ios - 如何使所有对象具有不同的 distanceInMeters?

iphone - 实时 GKMatch 断开连接问题

swift - 无法更改 Xcode 6 动态表中的行高

swift - 自动布局:ViewDidAppear 中的框架大小不正确

swift - 如何找出某个属性是否在用户的表中?

swift - 在 Swift 中使用基本身份验证的 POST 请求 + get params + post params(使用 Alamofire 或 RxSwift 或任何其他东西)

ios - 使用自动布局实现按钮的网格布局

ios - 在哪里为子类化的 uitableviewcell 创建自动布局约束?