生成随机数

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

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

在按钮上插入图片

1
2
3
4
5
6
Button(action: {
// flag was tapped
}) {
Image(self.countries[number])
.renderingMode(.original)
}

该renderingMode(.original)修饰符告诉SwiftUI呈现原始图像的像素,而不是试图重新着色他们作为一个按钮。

随机化数组顺序

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

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

忽略安全区域

背景渐变色,并忽略安全区域:

1
LinearGradient(gradient: Gradient(colors: [.blue, .black]), startPoint: .top, endPoint: .bottom).edgesIgnoringSafeArea(.all)

其中,.edgesIgnoringSafeArea(.all)可以忽略安全区域

胶囊形状

Swift中有四个内置形状:矩形,圆角矩形,圆形和胶囊形。我们将在这里使用胶囊:它确保最短边缘的角完全变圆,而最长边缘保持笔直–对于按钮来说看起来很棒。使我们的图像胶囊成形就像添加.clipShape(Capsule())修饰符一样容易,如下所示:

1
.clipShape(Capsule())

代码

今天的练习代码:

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

}

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 ???"), dismissButton: .default(Text("Continue")))
}
}
func flagTapped(_ number: Int) {
if number == correctAnswer{
scoreTitle = "Correct"

}else {
scoreTitle = "Wrong"
}

showingScore = true
}

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

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

参考资料

查看下一天的SwiftUI学习笔记

关于100days英文课程