alexanderwe/swiftui-theming
Effortless theming support in SwiftUI
Table of Contents
Installation
You can integrate swiftui-theming into your Xcode project as a Swift Package:
Xcode GUI
- 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.
Using Package.swift
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")Basic Usage
Step 1: Define Color Styles
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
}Step 2: Create a Theme
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)
}
}Make Your App Themeable
To enable theming in your app, inject a ThemeManager instance into your app's scenes.
Step 1: Initialize ThemeManager
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)
}
}Step 2: Access Theme Colors in Views
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))
}
}Step 3: Test your Theme in Previews
Use the withThemeManageror withTheme preview traits to inject your themes into SwiftUI previews.
#Preview(
traits: .withThemeManager(ThemeManager(initialTheme: .default))
) {
Text("Hello, world!")
.foregroundStyle(.themeColor(for: .primaryLabel))
}#Preview(
traits: .withTheme(.default)
) {
Text("Hello, world!")
.foregroundStyle(.themeColor(for: .primaryLabel))
}Documentation
Comprehensive documentation is available here.
License
This library is released under the MIT License. See the LICENSE file for details.
Package Metadata
Repository: alexanderwe/swiftui-theming
Homepage: https://alexanderwe.github.io/swiftui-theming/documentation/overview
Stars: 85
Forks: 1
Open issues: 0
Default branch: main
Primary language: swift
License: MIT
Topics: ios, macos, swiftui, theming, tvos, visionos, watchos
README: README.md