【发布时间】:2020-08-23 14:33:58
【问题描述】:
我正在关注 Hackingwithswift (https://www.hackingwithswift.com/books/ios-swiftui/animation-wrap-up) 的 100 天 swift 课程。项目 6 挑战 1 请求“返回猜旗项目并添加一些动画:当您点击正确的旗帜时,使其在 Y 轴上旋转 360 度”。 选择正确答案后,我能够使按钮旋转,但我不知道如何仅使选定的按钮旋转。
这是创建按钮的循环:
ForEach(0..<3){ number in
Button(action:{
self.flagTapped(number)
}){
FlagImage(number: number, countries: self.countries)
}
.rotation3DEffect(.degrees(self.animationAmount), axis: (x: 0, y: 1, z: 0))
}
这个flagTapped函数:
func flagTapped(_ number: Int){
if number == correctAswer{
scoreTitle = "Correct"
self.score += 1
withAnimation() {
self.animationAmount += 360
}
}
else{
scoreTitle = "Wrong. That is the flag of \(self.countries[number])"
self.score -= 1
}
showingMessage = true
}
感谢您的帮助
我发布了整个代码,希望得到一个答案,使第二个建议的选项起作用
struct ContentView: View {
@State private var countries = ["Estonia","France","Germany","Ireland","Italy","Nigeria","Poland","Russia","Spain","UK","US"].shuffled()
@State private var correctAnswer = Int.random(in: 0...2)
@State private var showingMessage = false
@State private var scoreTitle = ""
@State private var score = 0
@State private var animationAmount = 0.0
var body: some View {
ZStack{
LinearGradient(gradient: Gradient(colors: [.blue,.black]), startPoint: .top, endPoint: .bottom)
.edgesIgnoringSafeArea(.all)
VStack (spacing:30){
VStack{
Text("Tap the flag of")
.foregroundColor(.white)
Text(countries[correctAnswer])
.font(.largeTitle)
.fontWeight(.black)
.foregroundColor(.white)
}
ForEach(0 ..< 3) { number in
if number == self.correctAnswer {
Button(action: {
self.flagTapped(number)
}) {
FlagImage(number: number, countries: self.countries)
}
.rotation3DEffect(.degrees(self.animationAmount), axis: (x: 0, y: 1, z: 0))
} else {
Button(action: {
self.flagTapped(number)
}) {
FlagImage(number: number, countries: self.countries)
}
.rotation3DEffect(.degrees(self.animationAmount), axis: (x: 1, y: 0, z: 0))
}
}
Text("Your score is \(score)")
.foregroundColor(.white)
Spacer()
}
}
.alert(isPresented: $showingMessage){
Alert(title: Text(scoreTitle), message: Text(""), dismissButton: .default(Text("Continue")){
self.askQuestion()
})
}
}
func flagTapped(_ number: Int){
if number == correctAnswer{
scoreTitle = "Correct"
self.score += 1
withAnimation() {
self.animationAmount += 360
}
}
else{
scoreTitle = "Wrong. That is the flag of \(self.countries[number])"
self.score -= 1
withAnimation() {
self.animationAmount += 360
}
}
showingMessage = true
}
func askQuestion(){
countries.shuffle()
correctAnswer = Int.random(in: 0...2)
}
}
struct FlagImage: View {
var number: Int
var countries:[String]=[]
var body: some View {
Image(countries[number])
.renderingMode(.original)
.clipShape(Capsule())
.overlay(Capsule().stroke(Color.black, lineWidth: 1))
.shadow(color: .black, radius: 2)
}
}
【问题讨论】: