gpt4 book ai didi

ios - 如果约束改变( swift )

转载 作者:行者123 更新时间:2023-11-28 07:08:32 24 4
gpt4 key购买 nike

我正在尝试定义一个 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 属性)。 NSLayoutConstraint是一个类并且.constant一个CGFloat类声明中的属性。

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

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

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

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

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

可以将 NSLayoutConstraint 子类化并覆盖常量属性以拦截值更改,如下所示,除非这样做不会为您购买解决方案,因为 iOS 和 Interface Builder 不会使用或尊重您的子类。

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

}
}
}

关于ios - 如果约束改变( swift ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29492519/

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