首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >SwiftUI仅更改当前视图的导航标题颜色

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

Stack Overflow用户
提问于 2019-11-09 07:15:15
回答 2查看 681关注 0票数 1

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

代码语言:javascript
运行
复制
init() {
    UINavigationBar.appearance().largeTitleTextAttributes = [
        .foregroundColor: UIColor.red
    ]
}

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-11-09 20:36:24

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

代码语言:javascript
运行
复制
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
        })

    }
}
票数 2
EN

Stack Overflow用户

发布于 2020-06-01 12:06:21

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

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

检查此Link

代码语言:javascript
运行
复制
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))
    }

}

在那之后,像这样申请:

代码语言:javascript
运行
复制
.navigationBarColor(backgroundColor: .clear, titleColor: .white)

希望这能对你有所帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58774856

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档