笔记
本篇文章记录一下100 Days of SwiftUI
第21-22天的笔记内容
堆叠按钮
struct ContentView: View {
var countries = ["Estonia", "France", "Germany", "Ireland", "Italy", "Nigeria", "Poland", "Russia", "Spain", "UK", "US"]
var correctAnswer = Int.random(in: 0...2)
Zstack {
Color.blue
.ignoreSafeArea
VStack(spacing: 30) {
VStack {
Text("Tap the flag of")
.foregroundColor(.white)
Text(countries[correctAnswer])
.foregroundColor(.white)
}
ForEach(0..<3) { number in
Button {
// flag was tapped
} label: {
Image(countries[number])
.renderingMode(.original)
}
}
}
}
}
显示玩家的分数并发出警报
struct ContentView: View {
@State private var showingScore = false
@State private var scoreTitle = ""
// askQuestion函数中更改尚未标记为@State的视图属性是不允许的
@State private var countries = ["Estonia", "France", "Germany", "Ireland", "Italy", "Nigeria", "Poland", "Russia", "Spain", "UK", "US"].shuffled() // shuffled()方法自动为我们处理数组顺序的随机化
@State private var correctAnswer = Int.random(in: 0...2)
Zstack {
Color.blue
.ignoreSafeArea
VStack(spacing: 30) {
VStack {
Text("Tap the flag of")
.foregroundColor(.white)
Text(countries[correctAnswer])
.foregroundColor(.white)
}
ForEach(0..<3) { number in
Button {
flagTapped(number)
} label: {
Image(countries[number])
.renderingMode(.original)
}
}
}
.alert(scoreTitle, isPresented: $showingScore) {
Button("Continue", action: askQuestion)
} message: {
Text("Your score is ???")
}
}
func flagTapped(_ number: Int) {
if number == correctAnswer {
scoreTitle = "Correct"
} else {
scoreTitle = "Wrong"
}
showingScore = true
}
// 通过重新排列国家/地区并选择新的正确答案来重置游戏
func askQuestion() {
countries.shuffle()
correctAnswer = Int.random(in: 0...2)
}
}
设计我们的旗帜
// 背景色修改
Color.blue
.ignoresSafeArea()
// 替换为
LinearGradient(gradient: Gradient(colors: [.blue, .black]), startPoint: .top, endPoint: .bottom)
.ignoresSafeArea()
// 标题大小和样式修改
// font()修饰符来控制文本的大小和样式
// weight()调整字体的粗细
.font(.subheadline.weight(.heavy))
.font(.largeTitle.weight(.semibold))
// 优化旗帜图像
// 形状:.clipShape()
// 四个内置形状:矩形、圆角矩形、圆形和胶囊
.clipShape(Capsule()) // 胶囊形状
// 阴影:.shadow()
// 获取阴影的颜色、半径、X 和 Y 偏移量,但如果跳过颜色,我们会得到半透明的黑色,如果我们跳过 X 和 Y,则假定它们为 0(圆心)
.shadow(radius: 5)
升级我们的设计
// 调整背景,有趣的效果
RadialGradient(stops: [
.init(color: Color(red: 0.1, green: 0.2, blue: 0.45), location: 0.3),
.init(color: Color(red: 0.76, green: 0.15, blue: 0.26), location: 0.3),
], center: .top, startRadius: 200, endRadius: 400)
.ignoresSafeArea()
// 突出游戏部分
.frame(maxWidth: .infinity) // 调整大小,水平拉伸占据所有空间
.padding(.vertical, 20) // 垂直内边距
.background(.regularMaterial) // 模糊背景
.clipShape(RoundedRectangle(cornerRadius: 20)) // 裁剪为圆角矩形
、、