简体   繁体   English

使用WillSet属性观察器更改值

[英]Changing Values with WillSet Property Observer

I am attempting to create a UIView subclass. 我试图创建一个UIView子类。 In the initialization, I set minimum and maximum y-axis origin values I want the subclass to have. 在初始化中,我设置了子类要具有的最小和最大y轴原点值。 This view will be moved up and down programmatically, by user gestures or through an animation. 该视图将通过用户手势或动画以编程方式上下移动。 I was hoping I could use the willSet property user for this: 我希望可以为此使用willSet属性用户:

override var frame: CGRect {
    willSet {
        if newValue.origin.y > maximumOriginY {
            self.frame.origin.y = maximumOriginY
        }
        if newValue.origin.y < minimumOriginY {
            self.frame.origin.y = minimumOriginY
        }
    }
}

However, it doesn't seem to do anything. 但是,它似乎没有任何作用。 I have tried using DidSet property observer, but this resets the origin after it has been set, resulting in a stutter animation. 我尝试使用DidSet属性观察器,但是在设置原点后会重置原点,从而导致动画断断续续 Any ideas on how to get this to work with property observers or another way? 关于如何使它与财产观察员合作的任何想法? Thanks 谢谢

it is not possible to change the values within the willSet observer. willSet观察器中无法更改值。 overriding the getter and setter could work: 覆盖getter和setter可以工作:

override var frame: CGRect {
    get { return super.frame }
    set {
        var tempFrame = newValue
        tempFrame.origin.y = min(max(tempFrame.origin.y, minimumOriginY), maximumOriginY)
        super.frame = tempFrame
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM