DEV Community

ShoheOhtani
ShoheOhtani

Posted on

[SwiftUI] Change background color of NavigationView & Form

Image description

We need to modify NavigationView & Form.

NavigationView {
    VStack(alignment: .leading, spacing: 0.0) {
        Form {
            Section {
                NavigationLink(destination: EmptyView()) {
                    Text("-")
                }
                ...
            }
        }.backgroundColor(.black) ๐Ÿ‘ˆ
    }
    .navigationBarTitle("Settings", displayMode: .inline)
    .navigationBarColor(.black, tintColor: .white) ๐Ÿ‘ˆ
}
Enter fullscreen mode Exit fullscreen mode

Modify NavigationView

struct NavigationBarModifier: ViewModifier {
    var backgroundColor: UIColor?

    init(backgroundColor: UIColor?, tintColor: UIColor?) {
        self.backgroundColor = backgroundColor

        let coloredAppearance = UINavigationBarAppearance()
        coloredAppearance.configureWithTransparentBackground()
        coloredAppearance.backgroundColor = .clear
        coloredAppearance.titleTextAttributes = [.foregroundColor: tintColor as Any]
        coloredAppearance.largeTitleTextAttributes = [.foregroundColor: tintColor as Any]

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

    }

    func body(content: Content) -> some View {
        ZStack{
            content
            VStack {
                GeometryReader { geometry in
                    Color(self.backgroundColor ?? .clear)
                        .frame(height: geometry.safeAreaInsets.top)
                        .edgesIgnoringSafeArea(.top)
                    Spacer()
                }
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
extension View {

    func navigationBarColor(_ backgroundColor: Color?, tintColor: Color?) -> some View {
        self.modifier(NavigationBarModifier(backgroundColor: UIColor(backgroundColor ?? .white), tintColor: UIColor(tintColor ?? .black)))
    }

}
Enter fullscreen mode Exit fullscreen mode

Modify Form

struct FormModifier: ViewModifier {

    init(backgroundColor: UIColor?) {
        UITableView.appearance().backgroundColor = backgroundColor
    }

    func body(content: Content) -> some View {
        content
    }
}
Enter fullscreen mode Exit fullscreen mode
extension Form {

    func backgroundColor(_ backgroundColor: Color?) -> some View {
        self.modifier(FormModifier(backgroundColor: UIColor(backgroundColor ?? .white)))
    }

}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)