Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import SwiftUI
- struct ContentView: View {
- @State private var titleColor: UIColor = .black
- var body: some View {
- NavigationView {
- ScrollView {
- ScrollViewReader { proxy in
- VStack {
- ForEach(0..<100) { index in
- Text("Item \(index)")
- .padding()
- }
- }
- .background(GeometryReader { geo in
- Color.clear
- .preference(key: ScrollOffsetPreferenceKey.self, value: geo.frame(in: .global).minY)
- })
- }
- }
- .onPreferenceChange(ScrollOffsetPreferenceKey.self) { value in
- if value < 0 {
- titleColor = .red // Change to your desired color when scrolling
- } else {
- titleColor = .black // Change to your desired color when not scrolling
- }
- }
- .navigationBarTitle("Title", displayMode: .inline)
- .navigationBarColor(titleColor)
- }
- }
- }
- struct ScrollOffsetPreferenceKey: PreferenceKey {
- typealias Value = CGFloat
- static var defaultValue: CGFloat = 0
- static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
- value = nextValue()
- }
- }
- extension View {
- func navigationBarColor(_ color: UIColor) -> some View {
- self.modifier(NavigationBarModifier(backgroundColor: .clear, titleColor: color))
- }
- }
- struct NavigationBarModifier: ViewModifier {
- var backgroundColor: UIColor?
- var titleColor: UIColor?
- init(backgroundColor: UIColor?, titleColor: UIColor?) {
- self.backgroundColor = backgroundColor
- self.titleColor = titleColor
- let coloredAppearance = UINavigationBarAppearance()
- coloredAppearance.configureWithTransparentBackground()
- coloredAppearance.backgroundColor = backgroundColor
- coloredAppearance.titleTextAttributes = [.foregroundColor: titleColor ?? .black]
- coloredAppearance.largeTitleTextAttributes = [.foregroundColor: titleColor ?? .black]
- 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.clear
- .preference(key: NavigationBarHeightPreferenceKey.self, value: geometry.size.height)
- }
- Spacer()
- }
- }
- }
- }
- struct NavigationBarHeightPreferenceKey: PreferenceKey {
- typealias Value = CGFloat
- static var defaultValue: CGFloat = 0
- static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
- value = nextValue()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement