带来前面的副视图弄乱了UIView.animate

时间:2018-01-24 22:05:50

标签: swift animation uiview uibutton

我试图通过在动画发生之前根据bool值将两个UIViews放在另一个前面来尝试让两个UIViews交换到前面的位置,但是这样做可能会弄乱动画。动画只是简单地交换位置,但有时它并没有显示出来,而是显示它们都朝着相反的方向移动!

    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

    })

如果我将bringSubview移到前面,那里没有奇怪的动画效果,并且工作正常,但它不是我想要的。我希望他们在动画开始之前交换哪一个在前面。我甚至延迟补充..不起作用。

2 个答案:

答案 0 :(得分:1)

尝试使用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: {
        // ...

这里的想法是在我们开始要求动画之前让渲染树有机会处理子视图顺序的变化。

答案 1 :(得分:1)

self.view.layoutIfNeeded()

毫不拖延地完成这项工作