SwiftUI Theming is a library that enables seamless theming in SwiftUI across all Apple platforms, including iOS, macOS, tvOS, watchOS, and visionOS.
You can integrate swiftui-theming into your Xcode project as a Swift Package:
- Go to File > Add Package Dependency....
- Enter the repository URL:
https://github.com/alexanderwe/swiftui-theming
- Choose the library and add it to your desired target.
To add swiftui-theming via a Package.swift
file, include the following dependency:
.package(url: "https://github.com/alexanderwe/swiftui-theming", from: "0.1.0")
Then, add it to your target dependencies:
.product(name: "Theming", package: "swiftui-theming")
Before creating a new theme, define the color styles available in your app:
import Theming
extension ThemeColorStyle {
/// A style for primary labels
static let primaryLabel: Self = Self(name: "primaryLabel")
// Define additional styles as needed
}
With color styles defined, implement a method to create a theme:
import Theming
// MARK: - Available Themes
extension Theme {
static let `default`: Theme = .createDefaultTheme()
}
// MARK: - Theme Creation
extension Theme {
private static func createDefaultTheme() -> Theme {
let colors: Theme.ColorMap = [
.primaryLabel: ThemeColor(lightColor: .primary, darkColor: .primary)
]
return Theme(name: "Default", colors: colors)
}
}
To enable theming in your app, inject a ThemeManager
instance into your app's scenes.
Declare a @State
property to hold the ThemeManager
in your app definition:
import SwiftUI
import Theming
@main
struct MyApp: App {
@State var myThemeManager: ThemeManager = ThemeManager(initialTheme: .default)
var body: some Scene {
WindowGroup {
ContentView()
}
.withThemeManager(themeManager: myThemeManager)
}
}
Use the .themeColor
method to apply theme colors in your SwiftUI views:
struct ContentView: View {
var body: some View {
Text("Hello World")
.foregroundStyle(.themeColor(for: .primaryLabel))
}
}
Comprehensive documentation is available here.
This library is released under the MIT License. See the LICENSE file for details.