[英]tvOS SwiftUI TabView Dynamically Change Bar Color
I have a tvOS App with a TabView across the top.我有一个顶部有 TabView 的 tvOS 应用程序。 I want to use the background color of the TabView to indicate status.我想使用 TabView 的背景颜色来指示状态。 Initially it will be red and when something occurs in one of the views, I want to change the background color of the TabView to green.最初它是红色的,当其中一个视图发生某些事情时,我想将 TabView 的背景颜色更改为绿色。
I'm using the UITabBar.appearance().barTintColor = UIColor.red
in my init()
to set the initial color to red, but I can't find a way to change that to green later in execution.我在我的init()
中使用UITabBar.appearance().barTintColor = UIColor.red
将初始颜色设置为红色,但我找不到在稍后执行时将其更改为绿色的方法。
struct ContentView: View {
@State private var selection = 1
init() {
UITabBar.appearance().barTintColor = UIColor.red
}
var body: some View {
TabView (selection:$selection){
Tab1View()
.tabItem {
Image(systemName: "1.square.fill")
Text("Tab 1")
}
.tag(1)
Tab2View()
.tabItem {
Image(systemName: "2.square.fill")
Text("Tab 2")
}.tag(2)
Tab3View()
.tabItem {
Image(systemName: "3.square.fill")
Text("Tab 3")
}.tag(3)
}
.font(.headline)
.accentColor(.white)
.ignoresSafeArea()
}
}
You can use the code below.您可以使用下面的代码。
import SwiftUI
struct ContentView: View {
@State private var selectedTab = 0
var tabViewTitle = ["First Page","Second Page","Third Page"]
var body: some View {
VStack {
TabView(selection: $selectedTab){
Text(tabViewTitle[0])
.tag(0)
Text(tabViewTitle[1])
.tag(1)
Text(tabViewTitle[2])
.tag(2)
}
.frame(width: 300, height: 500)
.tabViewStyle(PageTabViewStyle())
.background(Color.purple)
.cornerRadius(15)
}
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
HStack(spacing: 16) {
ForEach(tabViewTitle, id: \.self) { index in
Rectangle()
.fill(self.selectedTab == tabViewTitle.firstIndex(where: {$0 == index}) ? Color.purple : Color.purple.opacity(0.5))
.frame(width: self.selectedTab == tabViewTitle.firstIndex(where: {$0 == index}) ? 16 : 12,height: self.selectedTab == tabViewTitle.firstIndex(where: {$0 == index}) ? 16 : 12)
}
}
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.