Swift如何使用动画淡入新图像然后淡出回到旧图像

时间:2018-08-14 13:52:12

标签: ios iphone swift animation uiviewanimation

我当前正在基于“ Simon Says”游戏创建游戏,其中用户必须按应用程序先前显示的相同顺序按下彩色按钮。这个序列越来越长,越来越困难。我在Illustrator中设计了按钮(4个彩色按钮同时处于按下状态和正常状态,因此有8张图像)。我目前有4个按钮,并将正常状态的图像连接到它。我现在想创建一个动画,以在正常状态和按下状态之间切换,以向用户简要显示他需要按下的按钮,然后再回到正常状态以显示用户需要按顺序按下的下一个按钮。 / p>

这是我的代码:

   UIView.transition(with: currentButton, duration: 0.7, options: .autoreverse, animations: {
        switch currentButton.tag {
        case 1: currentButton.setImage(#imageLiteral(resourceName: "greenpressed"), for: .normal)
        case 2: currentButton.setImage(#imageLiteral(resourceName: "redpressed"), for: .normal)
        case 3: currentButton.setImage(#imageLiteral(resourceName: "bluepressed"), for: .normal)
        case 4: currentButton.setImage(#imageLiteral(resourceName: "yellowpressed"), for: .normal)
        default:
            print("doPattern switch statement default")
        }
    }) { (complete) in
        if self.simonSays.currentButtonIndex == self.simonSays.getColorPattern.count - 1 {
            self.simonSays.currentButtonIndex = 0
            return self.patternIsFinished()
        }

        self.simonSays.currentButtonIndex += 1
        self.doPattern()
    }

这一次将状态更改为按下,但不会将其更改回其正常状态。我还尝试在动画的“完成”部分添加一个开关,但是状态根本没有改变。有办法用动画做到这一点吗?

1 个答案:

答案 0 :(得分:1)

您必须再次重置动画completion中的原始图像,因为您是setting图像。动画可能会来回移动,但分配尚未撤消。

但是在此之前,您应该为动画块内的按钮的alpha值设置动画。我不认为设置图像会产生动画。尝试这种逻辑。

func animateButton(with image: UIImage, defaultImage: UIImage! = nil) {
    UIView.animate(withDuration: 2, animations: {
            button.alpha = 0
        }) { (completed) in
            button.setImage(image, for: .normal)
            UIView.animate(withDuration: 2, animations: {
                button.alpha = 1
            }) {
                //Animate back only if current image is not default image
                if defaultImage != nil {
                    animateButton(with: defaultImage)
                } else {
                    // Your actual completion here
                }
            }
        }
}

现在使用所需的图像和默认图像调用此方法。

animateButton(requiredImage, defaultImage)

这是我头脑中的逻辑的非常粗糙的实现。但这会起作用。