どうも、ちょげ(@chogetarou)です。
TabViewのタブの色を変える方法を紹介します。
方法

TabViewのタブの色を変えるには、accentColor修飾子とUITabBarを使います。
選択中のタブの色
選択中のタブの色は、accentColor修飾子で変えることが出来ます。
まず、TabViewにaccentColor修飾子を付与します。
そして、accentColor修飾子の引数にタブの選択時の色を指定します。
TabView {
・・・
}
.accentColor(color) //選択しているタブの色を引数に指定
付与したaccentColorの引数の色が、TabViewの選択しているタブの色になります。
使用例

struct ContentView: View {
var body: some View {
VStack {
TabView {
PageView(text: "Home View")
.tabItem {
Image(systemName: "house.fill")
Text("home")
}
PageView(text: "Data View")
.tabItem {
Image(systemName: "folder.fill")
Text("Data")
}
PageView(text: "Person View")
.tabItem {
Image(systemName: "person.fill")
Text("Person")
}
}
.accentColor(.red)
}
}
}
非選択のタブの色
非選択のタブの色は、UITabBarで変えることが出来ます。
具体的には、initメソッドやonAppear修飾子で、UITabBar.appearance().unselectedItemTintColorに色を代入します。
init () {
//非選択中のタブの色を代入
UITabBar.appearance().unselectedItemTintColor = tabColor
}
UITabBar.appearance().unselectedItemTintColorに代入した色が、TabViewの非選択中のタブの色になります。
使用例

struct ContentView: View {
init() {
UITabBar.appearance().unselectedItemTintColor = .green.withAlphaComponent(0.3)
}
var body: some View {
VStack {
TabView {
PageView(text: "Home View")
.tabItem {
Image(systemName: "house.fill")
Text("home")
}
PageView(text: "Data View")
.tabItem {
Image(systemName: "folder.fill")
Text("Data")
}
PageView(text: "Person View")
.tabItem {
Image(systemName: "person.fill")
Text("Person")
}
}
}
}
}
まとめ
- 選択中のタブの色:accentColor修飾子で変える
- 非選択中のタブの色:UITabBarで変える
コメント