Photo by Laura Smetsers on Unsplash
That Wanaka tree
今天建立 Auckland, New Zealand 的公共游泳池的地圖清單。
Navigate to the ‘Assets’ directory and create a new folder named ‘PublicSwimmingPool’.
Inside the ‘PublicSwimmingPool’ folder, add images of public swimming pools from Auckland, New Zealand.
Press ‘Command + N’ to create a new SwiftUI file named ‘PublicSwimmingPoolsView’ and ‘PublicSwimmingPoolDetailView’.
PublicSwimmingPool 記得加 s .
建立 PublicSwimmingPool struct 遵循 Identifiable
協議
struct PublicSwimmingPool: Identifiable {
var id: UUID
var name: String
var photoCredit: String
var description: String
}
Q: 為什麼要用 Identifiable
:
使用 Identifiable
可以讓 SwiftUI 更有效地進行渲染和更新。例如,當數據發生變化時,SwiftUI 只會重新渲染已更改的項目,而不是整個列表,這有助於提高性能。
struct PublicSwimmingPoolsView: View {
var publicSwimmingPools: [PublicSwimmingPool]
var body: some View {
NavigationView {
List {
ForEach(publicSwimmingPools) { (item) in
NavigationLink(destination: PublicSwimmingPoolDetailView()) {
Text(item.name)
}
}
}
}
.navigationTitle(Text("Public Swimming Pools"))
.navigationViewStyle(StackNavigationViewStyle())
}
}
改寫 Previews
建立好 Mock publicSwimmingPools Array
struct PublicSwimmingPoolsView_Previews: PreviewProvider {
static let publicSwimmingPools = [
PublicSwimmingPool(id: UUID(), name: "Glen Innes Pool", photoCredit: "GlenInnesPool", description: "A hub for your family, Glen Innes Pool and Leisure Centre gets you active with multiple pool, fitness and leisure options. Join a group fitness class, learn to swim, have a splash in the water or book your kids into the onsite crèche – the choice is yours!"),
PublicSwimmingPool(id: UUID(), name: "Lloyd Elsmore Park Pool", photoCredit: "LloydElsmoreParkPool", description: "Lloyd Elsmore Park Pool and Leisure Centre is your local Pakuranga spot for all things active — jump in!")
]
static var previews: some View {
PublicSwimmingPoolsView(publicSwimmingPools: publicSwimmingPools)
}
}
Tips : PreviewProvider 註解掉 , option + command + return Canva 呼叫不出來。
Tips : 開模擬器,Canva 會暫停。
PublicSwimmingPoolsView 需要靠 Father View 傳遞數據
我把它理解為 React Props。
有人更好的解釋,歡迎留言~
ContentView 補上這段 code
PublicSwimmingPoolsView(publicSwimmingPools: publicSwimmingPools).tabItem {
NavigationLink(destination: PublicSwimmingPoolsView(publicSwimmingPools: publicSwimmingPools)) {
Label("Maps", systemImage: "map")
}.tag(2)
}
客串演出:東堂葵
下集待續