如果约束更改 (swift)

If constraint changed (swift)

我正在尝试定义一个 If 语句来检查约束的值是否已更改。

如果约束已更改{//执行此操作}

但我不确定如何将 DidChange 用于约束,或者这是否是正确的方法。

目前我正在使用大于或等于 Int。但这不是我追求的行为。有没有一种方法可以编写一个 if 语句来简单地检查值是否已更改?

if self.myConstraint.constant >= 50 {
        
            let delay = 0.1 * Double(NSEC_PER_SEC)
            let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
            
            dispatch_after(time, dispatch_get_main_queue(), {
        
                var iPath = NSIndexPath(forRow:         self.TheTableView.numberOfRowsInSection(1)-1, inSection: self.TheTableView.numberOfSections()-1)
                self.TheTableView.scrollToRowAtIndexPath(iPath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: false)
        
                println("\(countElements(fieldStatus))")
            })
        }

显然你在谈论 iOS AutoLayout 约束(因为你在示例中显示了 .constant 属性)。在 class 声明中,NSLayoutConstraint 是 class,.constantCGFloat 属性。

您需要从 UITraitEnvironment subclasses(其中 UIViewController 是一个)重写以下方法来检测约束集更改,因为这是约束的唯一方法常量会改变。 iOS 不会修改 .constant 属性,但是 你的 代码可能会修改,如果你修改 .constant,那么你就知道你在修改的时候修改它,所以不需要检查didSet()。但是 iOS 确实 根据平台和设备方向交换约束,您可以通过覆盖 traitCollectionDidChange 方法来拦截约束集更改:

override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) {
    // Accessing previousTraitCollection causes a crash
}

然后您可以遍历当前约束并检查 .constant 的值。

有些人发布了关于 willSet()didSet() 属性 的特定方法,但这仅适用于您在 您自己的 [=45= 中定义的属性] class。 NSLayoutConstraint 不是你自己的 class,你不能覆盖 .constant 属性 的行为,因为根据 Swift documentation on the extension keyword ]

NOTE Extensions can add new functionality to a type, but they cannot override existing functionality.

您可以可以 subclass NSLayoutConstraint 并重写常量属性 以拦截值更改,如下所示,但不会给您带来解决方案,因为iOS 并且 Interface Builder 不会使用或尊重您的子class。

import UIkit
class MyConstraint : NSLayoutConstraint {
    override var constant : CGFloat {
        get {
            return super.constant
        }
        set {
            // do something extra here
            super.constant = self.constant

       }
    }
}