设置`constraint.isActive = false`是否解除了约束?

时间:2017-09-13 21:38:37

标签: swift uiview nslayoutconstraint

说我想删除一个约束,传统上我会这样做:

view.removeConstraint(constraint)

但是,现在有了新的isActive方法来安装/卸载约束。

如果我执行以下操作:

constraint.isActive = false

是否会将其从内存中正确删除?

2 个答案:

答案 0 :(得分:5)

是的,

constraint.isActive = false

做同样的事情:

viewThatOwnsConstraint.removeConstraint(constraint)

因此,如果唯一坚持约束的是视图,那么这将正确地将其从内存中删除。

以下是证据:

let view = UIView()

weak var weakView: UIView? = nil
autoreleasepool {
  weakView = UIView()
}
assert(weakView == nil)

// Traditional way of removing constraints ensures that the constraint is deallocated

weak var weakConstraint: NSLayoutConstraint? = nil
autoreleasepool {
  weakConstraint = view.widthAnchor.constraint(equalToConstant: 10)
}
assert(weakConstraint == nil) // nothing is holding on to the constraint

autoreleasepool {
  weakConstraint = view.widthAnchor.constraint(equalToConstant: 10)
  view.addConstraint(weakConstraint!)
}
assert(weakConstraint != nil)

autoreleasepool {
  view.removeConstraint(weakConstraint!)
}
assert(weakConstraint == nil)

// New way of removing constraints:

assert(weakConstraint == nil)

autoreleasepool {
  weakConstraint = view.widthAnchor.constraint(equalToConstant: 10)
  weakConstraint!.isActive = true
}
assert(weakConstraint != nil)

autoreleasepool {
  weakConstraint!.isActive = false
}
assert(weakConstraint == nil)

答案 1 :(得分:0)

让我们说一下,如果您在不可重用的weak var中将约束出口定义为UIViewController,并用constraint.isActive = false将其禁用,则会将其从内存中删除。

但是,如果在诸如weak var之类的可重用视图中将约束出口定义为UICollectionViewCell,并且此UICollectionViewCell会在父视图中呈现为多个视图。通过constraint.isActive = false停用它不会将其从内存中删除,因为其他单元格仍保留该约束的引用。

将约束出口定义为(strong)var,执行constraint.isActive = false并不会将其从内存中删除,尽管已定义了UIView。