我目前正在创建一个基于游戏“Simon Says”的游戏,用户必须按照应用程序之前显示的相同顺序按下彩色按钮。序列越来越长,变得越来越困难。我在 Illustrator 中设计了按钮(4 个具有按下状态和正常状态的彩色按钮,所以有 8 个图像)。我目前有 4 个按钮并将正常状态图像连接到它。我现在想创建一个动画以在正常状态和按下状态之间切换,以简要地向用户显示他需要按下的按钮,然后变回正常状态以显示用户需要按顺序按下的下一个按钮。
这是我的代码:
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()
}
这会将状态更改为已按下,但不会将其更改回正常状态。我还尝试在动画的“完成”部分放置一个开关,但状态根本没有改变。有没有办法用动画来做到这一点?
最佳答案
您必须在动画完成
时再次重置原始图像,因为您正在设置
图像。动画可能会来回移动,但分配并未撤消。
但在此之前,您应该在动画 block 内为按钮的 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)
这是我脑海中逻辑的一个非常粗略的实现。但它会起作用。
关于ios - Swift 如何使用动画淡入新图像然后淡入旧图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51843134/