简体   繁体   中英

Changing Values with WillSet Property Observer

I am attempting to create a UIView subclass. In the initialization, I set minimum and maximum y-axis origin values I want the subclass to have. 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:

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. 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. overriding the getter and setter could work:

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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