<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by SimonZ89 on Medium]]></title>
        <description><![CDATA[Stories by SimonZ89 on Medium]]></description>
        <link>https://medium.com/@szwicker?source=rss-b21c39e74784------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*V4krLgWKjhVy-DPRckityw@2x.jpeg</url>
            <title>Stories by SimonZ89 on Medium</title>
            <link>https://medium.com/@szwicker?source=rss-b21c39e74784------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 11:37:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@szwicker/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Create a Simple Theming Architecture with SwiftUI]]></title>
            <link>https://medium.com/@szwicker/create-a-simple-theming-architecture-with-swiftui-510df4c20c8e?source=rss-b21c39e74784------2</link>
            <guid isPermaLink="false">https://medium.com/p/510df4c20c8e</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[theming]]></category>
            <category><![CDATA[personalization]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[SimonZ89]]></dc:creator>
            <pubDate>Wed, 14 May 2025 21:20:24 GMT</pubDate>
            <atom:updated>2025-05-15T08:43:00.278Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>While working on a SwiftUI app with a premium tier, I wanted to give Pro users the ability to choose their own app theme whether it’s light, dark, or a mix of both. I quickly realized that SwiftUI’s built-in support for dark mode is great, but not flexible enough when it comes to custom themes or letting the user pick between multiple styles.</p><p>So I set out to build a small theming architecture that’s easy to extend, simple to use on views, and flexible enough to support different visual styles, without cluttering the UI code. In this article, I’ll show you how the system works and how you can adapt it to your projects.</p><h3>The Idea</h3><ul><li>Allow users to select from multiple predefined themes</li><li>Support themes that are light-only, dark-only, or adapt to system appearance</li><li>Keep theme usage in views as lightweight and declarative as possible</li><li>Provide a clean and scalable architecture for injecting theme data via <strong>@Environment</strong></li><li>Make it easy to add new themes without touching existing UI code</li><li>Avoid hardcoded colors or scattered styling logic in views</li><li>Enable theme switching on runtime in a way that integrates smoothly with SwiftUI’s state system</li></ul><h3>Implementation</h3><p>To build a clean and scalable theming architecture, we’ll structure the solution across several lightweight files. This helps to keep the code modular and easy to maintain. We’ll define:</p><ul><li>A protocol to describe the structure of a theme</li><li>Different structs for the actual theme implementations (e.g. LightTheme, DarkTheme)</li><li>An enum to list available themes and handle selection logic</li><li>A simple way to persist the selected theme using UserDefaults</li><li>An extension of EnvironmentValues to inject the active theme into any view</li><li>A central Themer class conforming to <strong>@Observable</strong> to handle the current theme and switching on runtime</li></ul><p>Each piece plays a specific role and combined, they allow us to use .theme in any SwiftUI view with minimal boilerplate.</p><h4>Define our protocol</h4><p>To ensure all themes provide the same set of values (e.g. colors, backgrounds, gradients etc.), we define a ThemeProtocol, which acts as a blueprint every theme has to implement.</p><pre>import SwiftUI<br><br>protocol ThemeProtocol {<br>  var primary: Color { get }<br>  var mainBackground: Color { get }<br>  var cardElement: Color { get }<br>  var onboardingBackground: MeshGradient { get }<br>  var navigationButtonBackground: Color { get }<br>  var navigationTint: Color { get }<br>}</pre><p>You can define anything that’s related to your app’s visual style (e.g. Color, Font, Image, gradients, spacing, etc.)</p><h4>Creating our Theme</h4><p>With the ThemeProtocol in place, we can now create specific themes by implementing the required properties. Each theme is a simple struct, which makes it easy to maintain or extend.</p><p>As a starting point, we’ll implement two basic themes one for lightmode and one for darkmode based on the ThemeProtocol we defined.</p><pre>import SwiftUI<br><br>struct LightTheme: ThemeProtocol {<br>    let primary: Color = .black<br>    let mainBackground: Color = .white<br>    let cardElement: Color = Color(white: 0.95)<br>    let onboardingBackground: MeshGradient = MeshGradient.light<br>    let navigationButtonBackground: Color = Color.blue.opacity(0.1)<br>    let navigationTint: Color = .blue<br>}</pre><pre>import SwiftUI<br><br>struct DarkTheme: ThemeProtocol {<br>    let primary: Color = .white<br>    let mainBackground: Color = Color.black<br>    let cardElement: Color = Color(white: 0.15)<br>    let onboardingBackground: MeshGradient = MeshGradient.dark<br>    let navigationButtonBackground: Color = Color.white.opacity(0.1)<br>    let navigationTint: Color = .cyan<br>}</pre><p>You can freely adjust the colors or load them from your asset catalog. And if you have reusable color sets like Color(“BackgroundLight”), you can reference those. But keep in mind to avoid hardcoding.</p><h4><strong>Creating an Enum for our themes</strong></h4><p>To manage available themes and enable persistence via UserDefaults, we create an enum that maps each case to its actual theme struct. This also makes it easy to switch between variants of a theme if needed.</p><pre>enum ThemeID: String, CaseIterable {<br> case defaultLight<br> case defaultDark<br>}<br><br>extension ThemeID {<br> var ident: String {<br>  switch self {<br>  case .defaultLight: &quot;apptheme.default.light&quot;<br>  case .defaultDark: &quot;apptheme.default.dark&quot;<br>  }<br> }<br><br> var theme: ThemeProtocol {<br>  switch self {<br>  case .defaultLight: DefaultLightTheme()<br>  case .defaultDark: DefaultDarkTheme()<br>  }<br> }<br><br> var dark: ThemeID {<br>  switch self {<br>  case .defaultLight: .defaultDark<br>  default: self<br>  }<br> }<br><br> var light: ThemeID {<br>  switch self {<br>  case .defaultDark: .defaultLight<br>  default: self<br>  }<br> }<br>}</pre><p>Extend this enum later with more theme variants (e.g. blue, sunset, neon) and still use the same theming architecture without touching our UI code.</p><p>Themes that support only a single appearance, such as light-only or dark-only themes, don’t need to implement the light or dark computed properties.</p><p>However, for themes with both light and dark variants (e.g. sunsetLight and sunsetDark), the corresponding cases must be assigned to the light and dark properties. This ensures the correct variant is selected based on the system appearance.</p><h4>The Themer - Central Theme Manager</h4><p>To manage the currently globally active theme, we use a central Themer class.</p><ul><li>Storing the current theme (ThemeProtocol)</li><li>Tracking the current ColorScheme (.light or .dark)</li><li>Automatically switching between light and dark theme variants</li><li>Persisting the selected theme using UserDefaults</li><li>Smoothly animating transitions when themes or appearance change</li></ul><p>This keeps all theme-related logic in one place and makes switching themes easy, both in response to system appearance or on user selection.</p><pre>import SwiftUI<br><br>@Observable<br>class Themer {<br><br> private(set) var theme: ThemeProtocol<br> private(set) var colorScheme: ColorScheme = .light<br> @ObservationIgnored private(set) var themeID: ThemeID<br><br> init() {<br>  let userDefaultTheme = UserDefaults.theme<br>  self.themeID = userDefaultTheme<br>  self.theme = userDefaultTheme.theme<br> }<br><br> func setTheme(with themeID: ThemeID) {<br>  withAnimation {<br>   setThemeID(themeID)<br>  }<br> }<br><br> func setColorScheme(_ colorScheme: ColorScheme) {<br>  withAnimation {<br>   self.colorScheme = colorScheme<br>   setThemeID(themeID)<br>  }<br> }<br><br> private func setThemeID(_ themeID: ThemeID) {<br>  let themeScheme = colorScheme == .dark ? themeID.dark : themeID.light<br>  UserDefaults.theme = themeScheme<br>  self.themeID = themeScheme<br>  self.theme = themeScheme.theme<br> }<br>}</pre><p>Extend our UserDefaults to easily get and set the current selected theme.</p><pre>import Foundation<br><br>extension UserDefaults {<br>  static var theme: ThemeID {<br>    get { <br>      let rawValue = UserDefaults.standard.string(forKey: &quot;apptheme&quot;) ?? ThemeID.defaultLight.ident<br>      return ThemeID(rawValue: rawValue) ?? .defaultLight<br>    }<br>    set { <br>      UserDefaults.standard.set(newValue.ident, forKey: &quot;apptheme&quot;) <br>    }<br>  }<br>}</pre><p>If our app includes a widget and we want it to be synchronized with the selected theme, we can use a shared UserDefaults instance via an App Group. In that case, we have to be sure <strong>all theming-related files</strong> (e.g. struct, protocol, and enum) are also included in the widget extension target.</p><h4>EnvironmentValues and initializing the Themer</h4><p>To make the Themer accessible in all views, we extend EnvironmentValues with a custom key. In the <strong>@main</strong> App entry point, we inject the Themer using .environment() so it’s available throughout the view hierarchy.</p><p>This allows easy access via <strong>@Environment(</strong>\.themer<strong>)</strong> in any SwiftUI view.</p><pre>import SwiftUI<br><br>extension EnvironmentValues {<br>  @Entry var themer: Themer = .init()<br>}</pre><pre>import SwiftUI<br><br>@main<br>struct ExampleApp: App {<br>  @State private var themer: Themer = .init()<br><br>  var body: some Scene {<br>    WindowGroup {<br>      ContentView()<br>    }   <br>    .environment(\.themer, themer)<br>  }<br>}</pre><h4>Listen for system appearance changes</h4><p>The last missing piece is reacting to changes in system appearance. By observing the environment’s ColorScheme, we can automatically update the theme when the user switches between lightmode and darkmode in the system settings.</p><p>Since we can’t globally observe colorScheme changes, we use a workaround by embedding a background view (ColorSchemeTracker) that binds to the current ColorScheme. This view listens for changes and updates the Themer accordingly.</p><pre>import SwiftUI<br><br>struct ColorSchemeTracker: View {<br>  @Environment(\.colorScheme) private var colorScheme<br>  @Binding var current: ColorScheme<br><br>  var body: some View {<br>    Color.clear<br>      .onAppear {<br>        current = colorScheme<br>      }<br>      .onChange(of: colorScheme) { _, newValue in<br>        current = newValue<br>      }<br>  }<br>}</pre><p>Now we only have to refactor our App file to enable it to observe the change in system appearance.</p><pre>import SwiftUI<br><br>@main<br>struct ExampleApp: App {<br>  @State private var themer: Themer = .init()<br>  @State private var colorScheme: ColorScheme = .light<br><br>  var body: some Scene {<br>    WindowGroup {<br>      ContentView()<br>        .background(<br>          ColorSchemeTracker(current: $colorScheme)<br>            .onChange(of: colorScheme) {<br>              themer.setColorScheme($1)<br>            }<br>        )<br>    }   <br>    .environment(\.themer, themer)<br>  }<br>}</pre><p>With everything set up now, we can start using the theming system in our views to build UI that dynamically adapts to the selected theme.</p><h4>How our view could look like</h4><pre>import SwiftUI<br><br>struct ExampleView: View {<br><br>  @Environment(\.themer) private var themer<br><br>  var body: some View {<br>    VStack {<br>      Text(&quot;Hello World!&quot;)<br>        .padding()<br>        .background(themer.theme.primary)<br>    }<br>    .background(themer.theme.mainBackground.ignoresSafeArea())<br>  }<br>}</pre><h3>What&#39;s next?</h3><p>With the core theming architecture in place, you can take it even further:</p><ul><li>Add custom fonts, spacings, or a corner radius to your ThemeProtocol</li><li>Support more predefined themes with unique designs</li><li>Allow users to create and save their own themes</li><li>Synchronized themes across an app and widgets via App Group</li><li>Add theme previews in your settings screen</li><li>Accept JSON-based themes and define a Codable model to load theme styles dynamically, perfect for remote configs or theme sharing</li></ul><p>This approach gives us a flexible and powerful theming architecture that scales with our app and offers users real personalization.</p><p>I hope you enjoyed reading this article and that this approach helps to bring more personalization and flexibility to your SwiftUI projects.</p><p>Thanks for reading and happy theming!</p><p><strong><em>Feel free to share this article and follow me for more SwiftUI insights and architecture tips.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=510df4c20c8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>