bwash70
bwash70

Reputation: 1155

Getting animation height during animation in Swift / iOS

I am trying to get the current height of an animated UIView on my app.

I animate the UIView using:

function startFilling() {

    UIView.animateWithDuration(1.5, delay: 0, options: CurveEaseIn, animations: { () -> Void in
        self.filler.frame = CGRectMake(0, 0, self.frame.width, self.frame.height)
    }) { (success) -> Void in
        if success {
            self.removeGestureRecognizer(self.tap)
            self.delegate?.showSuccessLabel!()
        } else if !success {
            print("Not successful")
        }
    }
}

This animation is triggered using the .Begin state of a UILongPressGestureRecognizer like so:

if press.state == UIGestureRecognizerState.Began {
    startFilling()
} else if press.state == UIGestureRecognizerState.Ended {
    endFilling()
}

If the user stops pressing then the function endFilling is called and I need to get the current height of self.filler at the time they stop pressing.

The trouble is that the height always returns the expected end height in the animation (eg. self.frame.height), even if the press only lasted a portion of the duration time.

How can I get this height?

Upvotes: 2

Views: 1323

Answers (2)

saurabhgoyal795
saurabhgoyal795

Reputation: 1285

In swift4

self.filler.layer.presentation().bounds

Upvotes: 2

beyowulf
beyowulf

Reputation: 15331

That's not really how core animation works. Once you set a animatable value in a UIView.animateWithDuration block that value is set, whether the animation is completed or not. Thus when you ask for self.filler.frame after you call startFilling it is equal to CGRectMake(0, 0, self.frame.width, self.frame.height) regardless of whether it's 0.5 seconds or 5.0 seconds after you call startFilling. If you want to get the current value of the frame for what is on the screen, you need to say self.filler.layer.presentationLayer.frame. This should be used as a readonly value. If you want to interrupt the animation and have it come to rest at this value, you should say something like:

UIView.animateWithDuration(1.5, delay: 0, options: BeginFromCurrentState, animations: {
        self.filler.frame = self.layer.filler.presentationLayer.frame
    })

Upvotes: 3

Related Questions