挑战

最好的学习方法之一是尽可能频繁地编写自己的代码,因此,你应该尝试以下三种方式扩展此应用程序,以确保你完全了解正在发生的事情:

  • 添加一个@State属性来存储用户的分数,在答案正确与否时对其进行修改,然后将其显示在警报中。
  • 在标志正下方的标签中显示玩家的当前得分。
  • 如果有人选择了错误的标志,请在你的警报消息中告诉他们他们的错误-诸如“错误!那就是法国的国旗。”
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
//
// ContentView.swift
// GuessTheFlag
//
// Created by 张洪Hoo on 2020/1/20.
// Copyright © 2020 张洪Hoo. All rights reserved.
//

import SwiftUI

struct ContentView: View {
@State private var showingScore = false
@State private var scoreTitle = ""
@State private var score = 0

@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)

var body: some View {
ZStack {
LinearGradient(gradient: Gradient(colors: [.blue, .black]), startPoint: .top, endPoint: .bottom).edgesIgnoringSafeArea(.all)
VStack(spacing: 30.0) {
VStack {
Text("Tap the flag of")
.foregroundColor(Color.white)

Text(countries[correctAnswer])
.font(.largeTitle)
.fontWeight(.black)
.foregroundColor(Color.white)

Text("Score: \(score)")
.foregroundColor(Color.white)
.padding(.top)

}

ForEach(0 ..< 3) { number in
Button(action: {
self.flagTapped(number)
}) {
Image(self.countries[number])
.renderingMode(.original)
.clipShape(Capsule())
.overlay(Capsule().stroke(Color.black, lineWidth: 1))
.shadow(color: .black, radius: 2)
}
}
Spacer()

}

}.alert(isPresented: $showingScore) {
Alert(---
title: Text(scoreTitle), message: Text("Your score is \(score)"), dismissButton: .default(Text("Continue")))
}
}
func flagTapped(_ number: Int) {
if number == correctAnswer{
scoreTitle = "Correct"
self.score += 1

}else {
scoreTitle = "Wrong![]That's \(countries[number]) flag"
self.score -= 1
}

showingScore = true
}

func askQuestion(){
countries.shuffle()
correctAnswer = Int.random(in: 0...2)
}
}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

参考资料

查看下一天的SwiftUI学习笔记

关于100days英文课程