self.flagTapped(number)
切换为
showAnimation
。
there是可能的替代方法 - 更合适的外观将按钮移动到分离的视图中,并在需要时进行动画。在一些复制的简化代码上准备的demo(由于提供的快照中没有零件)。用Xcode 12 / iOS测试14.
true
struct DemoView: View {
let countries = ["flag-1", "flag-2", "flag-3", "flag-4"]
@State private var number: Int = -1
let correctAnswer = 1
var body: some View {
VStack {
ForEach(0 ..< 3) { number in
FlagButton(number: number, image: self.countries[number], answer: correctAnswer){
self.flagTapped(number)
}
}
}
}
private func flagTapped(_ number: Int) {
self.number = number
}
}
struct FlagButton: View {
let number: Int
let image: String
let answer: Int
var showAnimation = false
let action: () -> ()
@State private var animationAmount = Double.zero
var body: some View {
Button(action: {
if self.number == self.answer {
self.animationAmount += 360
}
action()
}) {
Image(image)
}
.rotation3DEffect(.degrees(number == answer ? self.animationAmount : 0), axis: (x: 0, y: 1, z: 0))
.opacity(self.showAnimation && number != answer ? 0.25 : 1)
.background(self.showAnimation && number != answer ? Color.red: nil)
.animation(.default)
}
}
选定的Flag var将有助于确定当前选择的标志,并将动画应用于特定图像,而不是按钮效果最好。
学习迅速,我今天偶然发现了与100天的Swiftui和我的解决方案相同的问题:
@State private var selectedFlag = -1 //Add this in your ContentView struct
ForEach(0..<3) { number in
Button {
flagTapped(number)
noOfQuestions += 1
if noOfQuestions == 8 {
showingEnd = true
}
if scoreTitle == "Correct Answer" {
score += 1
}
} label: {
Image(countries[number])
.renderingMode(.original)
.clipShape(Capsule())
.shadow(radius: 5)
.rotation3DEffect(.degrees(selectedFlag == number ? 360 : 0),
axis: (x: 0, y:1, z:0))
.opacity((selectedFlag == number || selectedFlag == -1) ? 1 : 0.25)
.animation(.default, value: selectedFlag )
.scaleEffect((selectedFlag == number || selectedFlag == -1) ? 1 : 0.75)
}
}
中,添加自己的这种方式,当我们单击按钮时,我们只是在进行回调,因此标志的逻辑 /验证仍然保留在主视图上。flag按钮:
@State
struct FlagButton: View {
let country: String
let id: Int
let flagTapped: (Int) -> Void
@State private var animationAmount = 0.0
var body: some View {
Button(){
withAnimation {
animationAmount += 360
}
flagTapped(id)
} label: {
Image("\(country)")
}
.rotation3DEffect(.degrees(animationAmount), axis: (x:0, y:1, z:0))
}
}
确定这是否是最好的方法。