SwiftUI仅更改当前视图的导航标题颜色

我知道我可以使用init来全局更改导航栏:

init() {
    UINavigationBar.appearance().largeTitleTextAttributes = [
        .foregroundColor: UIColor.red
    ]
}

我将如何仅针对当前视图执行此操作?我只想为当前视图而不是应用程序的所有视图设置导航标题颜色。

iceman4019 回答:SwiftUI仅更改当前视图的导航标题颜色

最简单的情况如下(您也可以在一些本地变量中存储/恢复以前的设置):

var body: some View {
    NavigationView(){
        List {
            // Some content is here
        }
        .navigationBarTitle("Title")
        .onAppear(perform: {
            UINavigationBar.appearance().largeTitleTextAttributes = [
                .foregroundColor: UIColor.red
            ]
        })
        .onDisappear(perform: {
            UINavigationBar.appearance().largeTitleTextAttributes = nil
        })

    }
}
,

不确定您现在是否遇到此问题。

我已经搜索了此问题并找到了一篇很棒的文章,您可以将导航栏样式的设置包装为视图修饰符。

选中此Link

struct NavigationBarModifier: ViewModifier {

    var backgroundColor: UIColor?
    var titleColor: UIColor?

    init(backgroundColor: UIColor?,titleColor: UIColor?) {
        self.backgroundColor = backgroundColor
        let coloredAppearance = UINavigationBarAppearance()
        coloredAppearance.configureWithTransparentBackground()
        coloredAppearance.backgroundColor = backgroundColor
        coloredAppearance.titleTextAttributes = [.foregroundColor: titleColor ?? .white]
        coloredAppearance.largeTitleTextAttributes = [.foregroundColor: titleColor ?? .white]

        UINavigationBar.appearance().standardAppearance = coloredAppearance
        UINavigationBar.appearance().compactAppearance = coloredAppearance
        UINavigationBar.appearance().scrollEdgeAppearance = coloredAppearance
    }

    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?,titleColor: UIColor?) -> some View {
        self.modifier(NavigationBarModifier(backgroundColor: backgroundColor,titleColor: titleColor))
    }

}

在那之后,像这样申请:

.navigationBarColor(backgroundColor: .clear,titleColor: .white)

希望这会对您有所帮助。

本文链接:https://www.f2er.com/3134655.html

大家都在问