Skip to content

Instantly share code, notes, and snippets.

@TuenTuenna
Created October 26, 2021 05:32
Show Gist options
  • Save TuenTuenna/746b64815a8741af930b21f7d579a3a6 to your computer and use it in GitHub Desktop.
Save TuenTuenna/746b64815a8741af930b21f7d579a3a6 to your computer and use it in GitHub Desktop.
## SwiftUi 네비게이션바 배경색 변경 방법입니다!

SwiftUi 네비게이션바 배경색 변경 방법입니다!

네비게이션바 모디파이어

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()
                }
            }
        }
    }
}

View 익스텐션에 추가

extension View {
    func navigationBarColor(backgroundColor: UIColor?, titleColor: UIColor?) -> some View {
        self.modifier(NavigationBarModifier(backgroundColor: backgroundColor, titleColor: titleColor))
    }
}

사용 예시

NavigationView {
    
}
.navigationBarColor(backgroundColor: .black, titleColor: .white)
@TuenTuenna
Copy link
Author

TuenTuenna commented Oct 26, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment