筆記
本篇文章記錄一下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)
}
}
}
}
}
顯示玩家的分數(shù)并發(fā)出警報
struct ContentView: View {
@State private var showingScore = false
@State private var scoreTitle = ""
// askQuestion函數(shù)中更改尚未標記為@State的視圖屬性是不允許的
@State private var countries = ["Estonia", "France", "Germany", "Ireland", "Italy", "Nigeria", "Poland", "Russia", "Spain", "UK", "US"].shuffled() // shuffled()方法自動為我們處理數(shù)組順序的隨機化
@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
}
// 通過重新排列國家/地區(qū)并選擇新的正確答案來重置游戲
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))
// 優(yōu)化旗幟圖像
// 形狀:.clipShape()
// 四個內置形狀:矩形沸停、圓角矩形龄恋、圓形和膠囊
.clipShape(Capsule()) // 膠囊形狀
// 陰影:.shadow()
// 獲取陰影的顏色、半徑、X 和 Y 偏移量曙寡,但如果跳過顏色,我們會得到半透明的黑色意狠,如果我們跳過 X 和 Y嘶卧,則假定它們?yōu)?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) // 調整大小俯萎,水平拉伸占據(jù)所有空間
.padding(.vertical, 20) // 垂直內邊距
.background(.regularMaterial) // 模糊背景
.clipShape(RoundedRectangle(cornerRadius: 20)) // 裁剪為圓角矩形
傲宜、、