SwiftUI-为什么我的TabBar忽略了init()中的设置颜色方法?

人气:98 发布:2023-01-03 标签: swiftui uitabbarcontroller uitabbar swiftui-tabview

问题描述

我有一个TabView。TabView中有两个视图-HomePageView和StatsPageView。HomePageView是第一个加载的视图。加载主页时,选项卡栏的背景为白色,而不是init()方法中设置的粉色背景。当我转到统计页面查看时,选项卡栏是粉红色的。当我回到主视图时,选项卡栏是粉红色的。为什么它装的是白色而不是粉色?我已经尝试将UITabBar.appearance().barTintColor = .systemPink放在ContentView init()方法中,我已经尝试在TabView本身上放置.onAppear(),我甚至尝试为UITabBarController构建一个扩展。所有人都做了完全相同的事情。够奇怪的

这里有一张gif:

https://giphy.com/gifs/O0aPkQfTXtn40WpFW1

以下是ContentView()的代码

struct ContentView: View {

@State private var selectedTab = 0
let numTabs = 2
let minDragTranslationForSwipe: CGFloat = 50

init() {
    UITabBar.appearance().barTintColor = .systemPink
    // this does nothing. does not set on first tab but does set second tab
}

var body: some View {
    TabView(selection: $selectedTab) {
        
        HomeView()
            .tabItem {
              Label("Home", systemImage: "house.fill")
            }.tag(0)
            .highPriorityGesture(DragGesture().onEnded({ self.handleSwipe(translation: $0.translation.width)}))
        
        StatsView()
            .environment(.managedObjectContext, CoreDataStack.shared.viewContext)
            .tabItem {
                Label("Profile", systemImage: "square.and.pencil")
            }.tag(1)
            .highPriorityGesture(DragGesture().onEnded({ self.handleSwipe(translation: $0.translation.width)}))
    }
    .onAppear(){
        UITabBar.appearance().barTintColor = .systemPink
        // this does NOT set on first tab but does when you go to the second tab and then sets on first tab when you go back
        print("in onAppear")
    }
    .accentColor(Color.green)
  // weirdly enough this sets onload on the first view
}

private func handleSwipe(translation: CGFloat) {
    if translation > minDragTranslationForSwipe && selectedTab > 0 {
        selectedTab -= 1
    } else  if translation < -minDragTranslationForSwipe && selectedTab < numTabs-1 {
        selectedTab += 1
    }
}
}

推荐答案

如果要设置TabBar背景,则应使用:

init() {
    UITabBar.appearance().backgroundColor = .systemPink
}

UITabBar.appearance().tintColor是项的颜色,在您的代码中,它将显示:

Label("Home", systemImage: "house.fill") and 
Label("Profile", systemImage: "square.and.pencil")

最后,UITabBar.appearance().barTintColor用于替换barStyle属性提供的内容。

2