简体   繁体   中英

before completion of UIView animation executing code in completion block

On button click I want to rotate view with 180 degree. After animation I want to hide and show image and label. But code in completion for hide and show image and label is executing before animation completion. Check below code and let me know am I wrong anywhere?

var animation = CABasicAnimation(keyPath: "transform.rotation.y")
    animation.fromValue = NSNumber(value: 0)
    animation.toValue = NSNumber(value: Double.pi)
    animation.repeatCount = 1
    animation.duration = 5.0

    UIView.animate(withDuration: 5.0, animations: {
        self.viewContainer.layer.add(animation, forKey: "rotation")
    }, completion: { finished in
        if finished {
            if self.strInfo == "Image" {
                self.strInfo = "Info"

                self.lblInfo.isHidden = false
                self.imageView.isHidden = true

                self.btnInfo.setBackgroundImage(UIImage(named:"close"), for: .normal)

            } else if self.strInfo == "Info"{
                self.strInfo = "Image"

                self.lblInfo.isHidden = true
                self.imageView.isHidden = false

                self.imageView.image = UIImage(named: self.strPhotoName)
                self.btnInfo.setBackgroundImage(UIImage(named:"info"), for: .normal)
            }
        }
    })

Adding animation to layer doesn't have a waiting time You need to make the animation logic inside the animation block completely such as changing frames or do this

self.viewContainer.layer.add(animation, forKey: "rotation")

DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {

    if self.strInfo == "Image" {
        self.strInfo = "Info"

        self.lblInfo.isHidden = false
        self.imageView.isHidden = true

        self.btnInfo.setBackgroundImage(UIImage(named:"close"), for: .normal)

    } else if self.strInfo == "Info"{
        self.strInfo = "Image"

        self.lblInfo.isHidden = true
        self.imageView.isHidden = false

        self.viewContainer.backgroundColor = .white

        self.imageView.image = UIImage(named: self.strPhotoName)

        self.btnInfo.setBackgroundImage(UIImage(named:"info"), for: .normal)
    }

}

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