这篇文章介绍了如何使用SwiftUI制作一个猜国旗应用。在这个应用中,我们学习了如何生成随机数、在按钮上插入图片、随机化数组顺序、背景渐变色、忽略安全区域以及胶囊形状等知识点。文章提供了完整的代码和详细的解释。
此内容根据文章生成,并经过人工审核,仅用于文章内容的解释与总结
投诉生成随机数
1
| var correctAnswer = Int.random(in: 0...2)
|
该Int.random(in:)
方法会自动选择一个随机数
在按钮上插入图片
1 2 3 4 5 6
| Button(action: { }) { 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 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
|
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英文课程