Creating a Dynamic Theme Switcher (Light/Dark Mode) in SwiftUI
Supporting both Light Mode and Dark Mode is essential for modern iOS applications. SwiftUI makes it incredibly easy to implement a dynamic theme switcher that allows users to toggle between light and dark modes seamlessly.
In this guide, we’ll build a theme switcher in SwiftUI that responds to system settings and allows manual user selection.
Understanding Dark Mode in SwiftUI
SwiftUI automatically adapts to system-wide light/dark mode settings. You can access the current color scheme using:
@Environment(\.colorScheme) var colorScheme
To explicitly set a color scheme for a view:
.environment(\.colorScheme, .dark) // or .light
Creating a Theme Manager
We’ll use AppStorage to persist user preferences and ObservableObject to manage the theme.
Step 1: Define ThemeManager
import SwiftUI
class ThemeManager: ObservableObject {
@AppStorage("isDarkMode") private var isDarkMode: Bool = false
var currentScheme: ColorScheme? {
isDarkMode ? .dark : .light
}
func toggleTheme() {
isDarkMode.toggle()
}
}
- Uses @AppStorage to persist user selection.
- Provides a toggleTheme() function to switch themes.
Implementing Theme Switcher in SwiftUI
Step 2: Create the Main View
struct ContentView: View {
@StateObject private var themeManager = ThemeManager()
var body: some View {
NavigationView {
VStack {
Text("Dynamic Theme Switcher")
.font(.largeTitle)
.padding()
Toggle("Enable Dark Mode", isOn: Binding(
get: { themeManager.currentScheme == .dark },
set: { _ in themeManager.toggleTheme() }
))
.padding()
}
.preferredColorScheme(themeManager.currentScheme)
.navigationTitle("Theme Switcher")
}
}
}
Explanation:
- @StateObject manages the theme state.
- Toggle allows users to switch themes manually.
- .preferredColorScheme() applies the selected theme.
Customizing UI for Light/Dark Mode
You can define different styles for each mode using colorScheme
:
struct ThemedView: View {
@Environment(\.colorScheme) var colorScheme
var body: some View {
VStack {
Text("Hello, SwiftUI!")
.foregroundColor(colorScheme == .dark ? .white : .black)
.padding()
.background(colorScheme == .dark ? Color.black : Color.white)
.cornerRadius(10)
}
}
}
Conclusion
With SwiftUI, implementing a dynamic theme switcher is simple and efficient. Using AppStorage, themes persist across app launches, and users can manually toggle between light and dark modes.
Comments
Post a Comment