猜国旗应用的复习。

随机化数组顺序

shuffled()方法会自动为我们处理随机化数组顺序。

1
var countries = ["Estonia", "France", "Germany", "Ireland", "Italy", "Nigeria", "Poland", "Russia", "Spain", "UK", "US"].shuffled()

胶囊形状裁剪

.clipShape(Capsule())

按钮中插入图片

1
2
Image("Estonia")
.renderingMode(.original)

生成随机数

1
var correctAnswer = Int.random(in: 0...2)

Int.random(in:)方法会自动选择一个随机数

代码

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
//
// ContentView.swift
// Practise2-3
//
// Created by 张洪Hoo on 2020/3/31.
// Copyright © 2020 张洪Hoo. All rights reserved.
//

import SwiftUI

struct ContentView: View {
@State private var counryList = ["Estonia", "France", "Germany", "Ireland", "Italy", "Nigeria", "Poland", "Russia", "Spain", "UK", "US"].shuffled()
@State private var question = Int.random(in: 0...2)
@State private var option = [String]()
@State private var showAlert = false

@State private var alertTitle = "猜对了!"
@State private var alertDescription = "当前分数为 ???"


var body: some View {
ZStack {

LinearGradient(gradient: Gradient(colors: [Color(#colorLiteral(red: 0.1017264351, green: 0.2405829132, blue: 0.8561289907, alpha: 1)), Color(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1))]), startPoint: .top, endPoint: .bottom)
.edgesIgnoringSafeArea(.all)


VStack {
Text("Tap the flag of")
.foregroundColor(Color.white)
Text("\(self.counryList[self.question])")
.font(.largeTitle)
.bold()
.foregroundColor(Color.white)
ForEach(0 ..< 3, id: \.self) { item in
Button(action: {
if item == self.question {
self.alertTitle = "猜对了!"
self.alertDescription = "当前分数为 ???"
self.showAlert = true
}else {
self.alertTitle = "猜错了!"
self.alertDescription = "正确答案是\(self.counryList[self.question]),当前分数为 ???"
self.showAlert = true
}
}) {
Image(self.counryList[item])
.renderingMode(.original)
.clipShape(Capsule())

}
.padding()

}


Spacer()
}

}

.alert(isPresented: $showAlert){
Alert(title: Text(alertTitle), message: Text(alertDescription), dismissButton: .default(Text("继续")){
self.askQuestion()
})

}
}

func askQuestion() {
counryList.shuffle()
question = Int.random(in: 0...2)

}
}

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

-w1792

SwiftPlayground 进度

-w1792