SwiftUI-為什么我的TabBar忽略了init()中的設置顏色方法? [英] SwiftUI - Why is my TabBar ignoring the set color method in the init()?

查看:0
本文介紹了SwiftUI-為什么我的TabBar忽略了init()中的設置顏色方法?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

我有一個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屬性提供的內容。

這篇關于SwiftUI-為什么我的TabBar忽略了init()中的設置顏色方法?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持IT屋!

查看全文
登錄 關閉
掃碼關注1秒登錄
發送“驗證碼”獲取 | 15天全站免登陸
全免费A级毛片免费看无码播放