Chewie The Chorkie
Chewie The Chorkie

Reputation: 5234

bringSubview to front messes up UIView.animate

I'm trying to get two UIViews to swap where they are in front by brining either one in front of another depending on a bool value before a animation happens, but doing this can mess up the animation. The animation simply swaps their positions, but sometimes it doesn't show this, and instead shows them both moving in opposite directions!

    if(self.takePhotoSelected){

        self.view.bringSubview(toFront: self.takePhotoBtn)

    }else{

        self.view.bringSubview(toFront: self.takeVideoBtn)

    }

    UIView.animate(withDuration: 0.25, delay: 0.1, options: [], animations: {

        let videoFrame = CGRect(x:self.takeVideoBtn.frame.origin.x, y: self.takeVideoBtn.frame.origin.y, width: self.takeVideoBtn.frame.width, height: self.takeVideoBtn.frame.height)
        let photoFrame = CGRect(x:self.takePhotoBtn.frame.origin.x, y: self.takePhotoBtn.frame.origin.y, width: self.takePhotoBtn.frame.width, height: self.takePhotoBtn.frame.height)

        self.takeVideoBtn.frame = photoFrame
        self.takePhotoBtn.frame = videoFrame

    }, completion: { (finished: Bool) in

    })

If I remove the bringSubview to front, there's no strange animation effect, and works fine, but it's not what I want. I want them to swap which one is in front before the animation even starts. I even added in a delay.. doesn't work.

Upvotes: 0

Views: 278

Answers (2)

Raphael Sacle
Raphael Sacle

Reputation: 32

self.view.layoutIfNeeded()

does the trick without delay

Upvotes: 1

matt
matt

Reputation: 535159

Try adding your delay with my delay function:

if(self.takePhotoSelected) {
    self.view.bringSubview(toFront: self.takePhotoBtn)
} else {
    self.view.bringSubview(toFront: self.takeVideoBtn)
}
delay(0.1) {
    UIView.animate(withDuration: 0.25, delay: 0.1, options: [], animations: {
        // ...

The idea here is to give the render tree a chance to deal with the change in subview order before we start asking for the animation.

Upvotes: 1

Related Questions