【问题标题】:Updating the UINavigationBar color only applies a tint, not sure why?更新 UINavigationBar 颜色只应用一种色调,不知道为什么?
【发布时间】:2020-06-05 02:44:49
【问题描述】:

所以....我有很多代码,在视图的初始化中,我更改了 UINavigationBar:

struct ContentView: View {
    init() {
        UINavigationBar.appearance().backgroundColor = .black
    }
    var body: some View {
        NavigationView {
            VStack {
                Text("Test")
            }.navigationBarTitle("TestBarTitle", displayMode: .inline)
        }
    }
}

由于某种原因,这只会使条显示为灰色(几乎就像它应用了透明的黑色滤镜一样)。我不确定,但我认为一定有一些代码弄乱了这个导航栏的变化。这可能是什么原因造成的?我希望导航栏字面上是黑色的。

旁注:当我删除 displayMode: .inline 时,导航栏显示为纯色而不是透明...如何以 displayMode: .inline 提供的方式维护导航栏设置?

【问题讨论】:

    标签: swift swiftui uinavigationbar


    【解决方案1】:

    我们可以创建一个名为“.navigationBarColor()”的自定义修饰符并像这样使用它:

    struct ContentView: View {
    
      var body: some View {
        NavigationView {
          VStack {
            Text("Test")
          }
          .navigationBarTitle("TestBarTitle", displayMode: .inline)
          .navigationBarColor(.black)
    
        }
      }
    }
    

    将此添加到您的 ContentView 文件中:

    struct NavigationBarModifier: ViewModifier {
    
      var backgroundColor: UIColor?
    
      init( backgroundColor: UIColor?) {
        self.backgroundColor = backgroundColor
        let coloredAppearance = UINavigationBarAppearance()
        coloredAppearance.configureWithTransparentBackground()
        coloredAppearance.backgroundColor = .clear
        coloredAppearance.titleTextAttributes = [.foregroundColor: UIColor.white]
        coloredAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white]
    
        UINavigationBar.appearance().standardAppearance = coloredAppearance
        UINavigationBar.appearance().compactAppearance = coloredAppearance
        UINavigationBar.appearance().scrollEdgeAppearance = coloredAppearance
        UINavigationBar.appearance().tintColor = .white
    
      }
    
      func body(content: Content) -> some View {
        ZStack{
          content
          VStack {
            GeometryReader { geometry in
              Color(self.backgroundColor ?? .clear)
                .frame(height: geometry.safeAreaInsets.top)
                .edgesIgnoringSafeArea(.top)
              Spacer()
            }
          }
        }
      }
    }
    
    extension View {
    
      func navigationBarColor(_ backgroundColor: UIColor?) -> some View {
        self.modifier(NavigationBarModifier(backgroundColor: backgroundColor))
      }
    
    }
    
    


    查看 2020 年 3 月 10 日发布的这篇文章。

    https://filipmolcik.com/navigationview-dynamic-background-color-in-swiftui/

    【讨论】:

    • 您可以将该扩展添加到单独的文件中以节省空间,这样您就可以在项目的其他部分重复使用它。
    猜你喜欢
    • 2021-09-14
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    • 2015-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多