SwiftUI导航栏的一些配置(背景色,字体颜色,大小)

1.创建ViewModifier

//修改导航栏的颜色
struct StatusBarColorModifier: ViewModifier {
    var color: UIColor
    init(color: UIColor) {
        self.color = color
        let navibarAppearance = UINavigationBarAppearance()
        navibarAppearance.configureWithTransparentBackground()
        //修改背景的颜色
        navibarAppearance.backgroundColor = color
        //设置字体的颜色和大小
        navibarAppearance.titleTextAttributes = [
            .foregroundColor:UIColor.white,
            .font:UIFont.monospacedSystemFont(ofSize: 17, weight: .black)
        ]
        
        UINavigationBar.appearance().standardAppearance = navibarAppearance
        UINavigationBar.appearance().compactAppearance = navibarAppearance
        UINavigationBar.appearance().scrollEdgeAppearance = navibarAppearance
    }
    
    func body(content: Content) -> some View {
        ZStack{
            content
            VStack {
                GeometryReader { geometry in
                    Color(self.color)
                        .frame(height: geometry.safeAreaInsets.top)
                        .edgesIgnoringSafeArea(.top)
                    Spacer()
                }
            }
        }
    }
}

2.创建一个View的扩展方便调用

extension View {
    func statusBarColor(_ color: Color) -> some View {
        self.modifier(StatusBarColorModifier(color: UIColor(color)))
    }
}

3.调用

NavigationView {
            .navigationBarHidden(false)
            .navigationBarTitle(Text("导航栏"), displayMode: .inline)
        }
        .statusBarColor(.red)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容