Photo by Tom Sakai on Unsplash
Mid-Winter Queenstown, New Zealand
Press ‘Command + N’ to create a new Swift file named ‘GlobalSettings’
class GlobalSettings: ObservableObject {
@Published var selectedTabIndex: Int = 0
}
這是使用SwiftUI的基本方式來創建一個可觀察的物件。這意味著當 selectedTabIndex
的值更改時,任何觀察此物件的視圖將會重新渲染。
要使用 GlobalSettings
:
在你的某個視圖中,創建一個這個類的實例:
@ObservedObject var settings = GlobalSettings()
然後,你可以使用 settings.selectedTabIndex
並根據需要進行修改。當 selectedTabIndex
改變時,視圖會自動更新。
在 ContentView
struct ContentView: View {
@ObservedObject var settings = GlobalSettings()
TabView 裡新增
SettingsView().tabItem {
NavigationLink(destination: SettingsView()) {
Label("Settings", systemImage: "gearshape")
}
}.tag(4)
FourTargetButtonView(settings: settings).tabItem {
NavigationLink(destination: FourTargetButtonView(settings: settings)) {
Label("hands", systemImage: "hands.sparkles")
}
}.tag(5)
Tips: tab bar 最多5個,不要太貪心😙
struct FourTargetButtonView: View {
@ObservedObject var settings: GlobalSettings
var body: some View {
VStack(spacing: 20) {
HStack(spacing: 20) {
TargetButtonView(iconName: "house", tagNumber: 1, settings: settings)
TargetButtonView(iconName: "list.clipboard.fill", tagNumber: 2, settings: settings)
}
HStack(spacing: 20) {
TargetButtonView(iconName: "map", tagNumber: 3, settings: settings)
TargetButtonView(iconName: "gearshape", tagNumber: 4, settings: settings)
}
}
.padding(.horizontal, 20)
}
}
struct TargetButtonView: View {
var iconName: String
var tagNumber: Int
@ObservedObject var settings: GlobalSettings
var buttonSize: CGFloat {
return (UIScreen.main.bounds.width - 60) / 2
}
var body: some View {
Button(action: {
// 在此處放置按鈕的動作
settings.selectedTabIndex = tagNumber
}) {
Image(systemName: iconName)
.resizable() // 使圖標可調整大小
.frame(width: buttonSize - 80, height: buttonSize - 80) // 設定按鈕的寬度和高度以保持正方形,減去左右各40像素的間距
.padding(40) // 為圖標增加40像素的間距
.background(RoundedRectangle(cornerRadius: buttonSize / 4).fill(Color.blue)) // 等比例圓角
.foregroundColor(.white)
}
}
}
不義遊戲跳轉頁面完成
👏🏻👏🏻👏🏻👏🏻👏🏻👏🏻逃不出我的手掌心吧
什麼你說 @ObservedObject 會搞的很多層傳值,此案例就傳三層,有更好的解法!
沒錯,埋下這伏筆
這就是我給你的試煉
提示:@StateObject or @EnvironmentObject
燃燒你的熱情
下集待續 💪🏻