1

I am implementing a TabView in SwiftUI, I want to detect when the colorScheme changes because I implemented a custom page indicator with colors which depends of colorScheme. tabView contains a method named onAppear() where I call to setUpApariencie() but if I change the colorScheme when the app is running, the changes on de page indicator dont work. I show you the code:

}
                .tabViewStyle(.page(indexDisplayMode: .always))
                .indexViewStyle(.page(backgroundDisplayMode: .always))
                
                .frame( height: heigth * 0.4)
                .onAppear(){
                    setupAppearance()
                }
                
                
            }
            
            
        }
        
    }
    
    
}
func setupAppearance() {
    UIPageControl.appearance().currentPageIndicatorTintColor = colorScheme == .light ? .black : .white
    UIPageControl.appearance().pageIndicatorTintColor = UIColor.black.withAlphaComponent(0.2)
}

one more thing, I dont know why withAlphaComponent doesnt do anything. thanks.

agmcoder
  • 195
  • 1
  • 8

2 Answers2

0

You can watch changes to the theme the following way:

class AppThemeViewModel: ObservableObject {
    
    @AppStorage("isDarkMode") var isDarkMode: Bool = true                           // also exists in DarkModeViewModifier()
    
}

struct DarkModeViewModifier: ViewModifier {
    @ObservedObject var appThemeViewModel: AppThemeViewModel = AppThemeViewModel()
    
    public func body(content: Content) -> some View {
        content
            .preferredColorScheme(appThemeViewModel.isDarkMode ? .dark : appThemeViewModel.isDarkMode == false ? .light : nil)
    }
}

For more details look here

Arturo
  • 3,254
  • 2
  • 22
  • 61
0

This should do the trick:

struct MyView: View {
    @Environment(\.colorScheme) var colorScheme
    
    Text("Hello")
    .onChange(of: colorScheme) { newValue in
         print("\(newValue)")
    }
}
James Toomey
  • 5,635
  • 3
  • 37
  • 41