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

Ios SwiftUI仅更改当前视图的导航标题颜色,ios,swift,swiftui,Ios,Swift,Swiftui,我知道我可以使用init全局更改导航栏: init() { UINavigationBar.appearance().largeTitleTextAttributes = [ .foregroundColor: UIColor.red ] } 如何仅在当前视图中执行此操作?我只想设置当前视图的导航标题颜色,而不是应用程序的所有视图。最简单的情况如下(您也可以在某些本地变量中存储/恢复以前的设置): 不确定您现在是否有此问题 我已经搜索了这个问题,找到了一篇关于这

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

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

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

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


不确定您现在是否有此问题

我已经搜索了这个问题,找到了一篇关于这个问题的好文章,你可以把导航栏样式的设置包装成一个视图修改器

看看这个

之后,按如下方式申请:

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

希望这能对您有所帮助。

对于子视图,您将如何做到这一点?这似乎不适用于子视图,只适用于根视图。
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)