◉RORK LABJP
●SUBDOMAIN — Rork can now connect your web app to a subdomain only, leaving your root domain and www untouched (12/1)●UPDATES — expo-updates 58.0.23 fixes Android release builds embedding a stale runtime version●FLASH END — Intro pricing for Gemini Flash models ends 12/31, 29 days from now. Time to recheck AI feature costs●HMR — Some report the dev server picking up another server's bundle and then exiting●FIRST VIEW — Map the first screen for a normal launch, a notification, and a link, and back navigation stops surprising you●CARBON — Gemini 4 Carbon and Argon are now at standard rates: $4.00 input, $20.00 output per 1M tokens●SUBDOMAIN — Rork can now connect your web app to a subdomain only, leaving your root domain and www untouched (12/1)●UPDATES — expo-updates 58.0.23 fixes Android release builds embedding a stale runtime version●FLASH END — Intro pricing for Gemini Flash models ends 12/31, 29 days from now. Time to recheck AI feature costs●HMR — Some report the dev server picking up another server's bundle and then exiting●FIRST VIEW — Map the first screen for a normal launch, a notification, and a link, and back navigation stops surprising you●CARBON — Gemini 4 Carbon and Argon are now at standard rates: $4.00 input, $20.00 output per 1M tokens
Articles/Dev Tools
⬡ Dev Tools/2026-05-12Advanced

Building a Shared UI Component Library with Swift Package Manager in Rork Max

A practical guide to building a shared SwiftUI component library with Swift Package Manager for indie developers running multiple apps — eliminate duplicate code across wallpaper, healing, and similar app families.

Rork Max236Swift Package ManagerSwiftUI66Indie Dev40Component DesignMulti-App

It was a late evening spent on the tap feedback of a wallpaper card. I tightened the spring response from 0.4 seconds to 0.3, and the card finally felt right under my thumb. The next morning I opened a different app in the family — a healing app with what looked like the same card — and it was still moving with the old value. The fix hadn't crossed the wall between projects.

Rork Max makes this drift easier to produce. The SwiftUI it generates is good, but each generation sees one project at a time. Ask for a card in two apps and you get two slightly different cards: a corner radius off by a couple of points, a shadow that's a touch heavier. They multiply quietly with every app you add.

The short answer is a shared UI library built with Swift Package Manager (SPM): one fix, one test, and each app picks it up when you bump the version. One more thing up front — the card code in the first version of this article didn't compile as written, and Color(hex:) was used without ever being defined. Both are corrected below, so the steps now run end to end.


Why Rork Max Projects Need a Shared Package

Rork Max generates SwiftUI scoped to a single app, which is sensible — it can't know about your other projects. But for a family of related apps, three things scatter:

Theme colors. Each project keeps its own asset-catalog entry, with its own RGB values and dark-mode variants. Moving a brand color from #7B68EE to #6A5ACD means opening every project.

Animation constants. Values like spring(response: 0.4, dampingFraction: 0.75) are pasted into individual files, so changing the feel of the app is the same chore repeated.

Component drift. "A card" exists everywhere, but one app rounds at 16 pt and another at 14 pt. A 1–2 pt gap is hard to name, yet users read it as a faint roughness.

With a shared package, these collapse into one Package.swift and a handful of source files.


Designing the Library Boundary

Before writing code, I sort things into "what never changes" and "what differs per app." If you skip this step, the library slowly absorbs app-specific code.

CategoryLives inExamples
Stable across appsLibraryAnimation presets, shadow/blur/corner-radius tokens, ButtonStyles, cards, banners, tag chips, thin haptics wrappers
Differs per appAppBrand colors, font families, app-specific icons, business logic
Touches an external SDKApp (or a separate target)AdMob banners, analytics, purchase SDK wrappers

I learned the last row the hard way. My first library included a wrapper around AdMob's GADBannerView, and the SDK dependency spread into apps that don't even show ads. Every build felt heavier than it should have. These days I check against a single sentence: the library holds the feel that doesn't change; brand decisions and SDKs stay in the app.


Creating the Swift Package

Create the package next to your app projects:

mkdir -p ~/Developer/DoliceUIKit
cd ~/Developer/DoliceUIKit
swift package init --type library --name DoliceUIKit

Set the minimum to iOS 17 so @Observable is available:

// Package.swift
// swift-tools-version: 5.10
import PackageDescription
 
let package = Package(
    name: "DoliceUIKit",
    platforms: [
        .iOS(.v17)
    ],
    products: [
        .library(
            name: "DoliceUIKit",
            targets: ["DoliceUIKit"]
        ),
    ],
    dependencies: [],
    targets: [
        .target(
            name: "DoliceUIKit",
            dependencies: [],
            path: "Sources/DoliceUIKit"
        ),
        .testTarget(
            name: "DoliceUIKitTests",
            dependencies: ["DoliceUIKit"],
            path: "Tests/DoliceUIKitTests"
        ),
    ]
)

Keep dependencies empty. If you eventually need an external SDK, put it in its own target.


The Theme Injection System

Each app needs its own colors and fonts, injected through SwiftUI's environment. First, the helper the samples rely on. SwiftUI has no built-in hex initializer, so without this the build fails:

// Sources/DoliceUIKit/Theme/Color+Hex.swift
 
import SwiftUI
 
public extension Color {
    /// Builds a Color from "#7B68EE" or "7B68EE"
    init(hex: String) {
        let cleaned = hex.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
        var value: UInt64 = 0
        Scanner(string: cleaned).scanHexInt64(&value)
        let r = Double((value >> 16) & 0xFF) / 255
        let g = Double((value >> 8) & 0xFF) / 255
        let b = Double(value & 0xFF) / 255
        self.init(.sRGB, red: r, green: g, blue: b, opacity: 1)
    }
}

Then the theme protocol and the environment key:

// Sources/DoliceUIKit/Theme/AppTheme.swift
 
import SwiftUI
 
/// Each app conforms to this and injects it at the root
public protocol AppThemeable: Sendable {
    var primary: Color { get }
    var secondary: Color { get }
    var surface: Color { get }
    var onSurface: Color { get }
    var fontTitle: Font { get }
    var fontBody: Font { get }
    var fontCaption: Font { get }
}
 
/// Default theme for development and previews
public struct DefaultAppTheme: AppThemeable {
    public var primary: Color { Color(hex: "#7B68EE") }
    public var secondary: Color { Color(hex: "#48D1CC") }
    public var surface: Color { Color(.systemBackground) }
    public var onSurface: Color { Color(.label) }
    public var fontTitle: Font { .system(.title2, design: .rounded, weight: .bold) }
    public var fontBody: Font { .system(.body) }
    public var fontCaption: Font { .system(.caption) }
 
    public init() {}
}
 
private struct AppThemeKey: EnvironmentKey {
    static let defaultValue: any AppThemeable = DefaultAppTheme()
}
 
public extension EnvironmentValues {
    var appTheme: any AppThemeable {
        get { self[AppThemeKey.self] }
        set { self[AppThemeKey.self] = newValue }
    }
}

The Sendable requirement is there so the static let in the environment key doesn't turn into a concurrency error when you move to the Swift 6 language mode. For how those diagnostics read in practice, see Swift 6 Strict Concurrency Migration with MainActor and Sendable.

In each app, define one conforming type and inject it:

// WallpaperApp/WallpaperAppTheme.swift
import SwiftUI
import DoliceUIKit
 
struct WallpaperAppTheme: AppThemeable {
    var primary: Color { Color(hex: "#FF6B9D") }
    var secondary: Color { Color(hex: "#FFB347") }
    var surface: Color { Color(.systemBackground) }
    var onSurface: Color { Color(.label) }
    var fontTitle: Font { .custom("ZenMaruGothic-Bold", size: 20) }
    var fontBody: Font { .custom("ZenMaruGothic-Regular", size: 16) }
    var fontCaption: Font { .custom("ZenMaruGothic-Regular", size: 12) }
}
 
@main
struct WallpaperApp: App {
    var body: some Scene {
        WindowGroup {
            RootView()
                .environment(\.appTheme, WallpaperAppTheme())
        }
    }
}

The payoff: add a new field to AppThemeable and every app that hasn't implemented it fails to compile. A missed brand update stops depending on anyone's memory.

One caution on fonts. Bundle custom font files such as ZenMaruGothic in each app target, not in the library. If the name doesn't match, Font.custom doesn't raise an error — it quietly falls back to the system font — so check on a real device once.


Building the Card Component

The first version of this article passed style == .flat ? RoundedRectangle(...) : nil straight into overlay. There is no overlay that accepts nil as a View, so that never compiled. Use an if inside the overlay closure instead:

// Sources/DoliceUIKit/Components/ContentCard.swift
 
import SwiftUI
 
public struct ContentCard<Content: View>: View {
    @Environment(\.appTheme) private var theme
    @Environment(\.colorScheme) private var colorScheme
 
    private let content: Content
    private let style: CardStyle
 
    public enum CardStyle {
        case standard   // Subtle shadow
        case elevated   // Stronger shadow, premium feel
        case flat       // No shadow, thin border
    }
 
    public init(style: CardStyle = .standard, @ViewBuilder content: () -> Content) {
        self.style = style
        self.content = content()
    }
 
    public var body: some View {
        content
            .background(cardBackground)
            .clipShape(RoundedRectangle(cornerRadius: cardCornerRadius))
            .shadow(color: shadowColor, radius: shadowRadius, x: 0, y: shadowY)
    }
 
    private var cardBackground: some View {
        theme.surface
            .overlay {
                if style == .flat {
                    RoundedRectangle(cornerRadius: cardCornerRadius)
                        .strokeBorder(theme.primary.opacity(0.2), lineWidth: 1)
                }
            }
    }
 
    private var cardCornerRadius: CGFloat { 16 }
 
    private var shadowColor: Color {
        switch style {
        case .standard: return Color.black.opacity(colorScheme == .dark ? 0.3 : 0.08)
        case .elevated: return theme.primary.opacity(0.2)
        case .flat:     return .clear
        }
    }
 
    private var shadowRadius: CGFloat {
        switch style {
        case .standard: return 8
        case .elevated: return 20
        case .flat:     return 0
        }
    }
 
    private var shadowY: CGFloat {
        switch style {
        case .standard: return 4
        case .elevated: return 8
        case .flat:     return 0
        }
    }
}

Compare it with what Rork Max tends to generate in two separate projects:

Before — two apps, two near-identical cards:

// In WallpaperApp
struct WallpaperCard: View {
    var body: some View {
        content
            .background(Color(.systemBackground))
            .clipShape(RoundedRectangle(cornerRadius: 16))
            .shadow(color: .black.opacity(0.08), radius: 8, x: 0, y: 4)
    }
}
 
// In HealingApp — almost the same, but not quite
struct HealingCard: View {
    var body: some View {
        content
            .background(Color(.systemBackground))
            .clipShape(RoundedRectangle(cornerRadius: 14))   // different
            .shadow(color: .black.opacity(0.1), radius: 6, x: 0, y: 3)  // different
    }
}

After — one component, theme-aware:

ContentCard(style: .elevated) {
    WallpaperThumbnailView(item: wallpaper)
}

A 16 pt versus 14 pt corner, or 0.08 versus 0.1 shadow opacity, no longer depends on which project you happened to be in.


Animation Presets

Animation values drift between projects too. Pin them down as Animation extensions:

// Sources/DoliceUIKit/Animation/AnimationPresets.swift
 
import SwiftUI
 
public extension Animation {
    /// Standard spring for tap feedback and state changes
    static let doliceSpring = Animation.spring(
        response: 0.4,
        dampingFraction: 0.75,
        blendDuration: 0
    )
 
    /// Quick snap for button presses
    static let doliceSnap = Animation.spring(
        response: 0.25,
        dampingFraction: 0.8,
        blendDuration: 0
    )
 
    /// Smooth ease for screen transitions
    static let doliceEase = Animation.easeOut(duration: 0.35)
 
    /// Crossfade when wallpapers or backgrounds switch
    static let doliceContentTransition = Animation.easeInOut(duration: 0.5)
}
 
/// Press effect that sinks slightly on touch
public struct DolicePressEffect: ButtonStyle {
    public init() {}
 
    public func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .scaleEffect(configuration.isPressed ? 0.94 : 1.0)
            .opacity(configuration.isPressed ? 0.85 : 1.0)
            .animation(.doliceSnap, value: configuration.isPressed)
    }
}

An earlier draft left an unused @Environment(\.appTheme) inside DolicePressEffect. A button style that never reads the theme doesn't need it, so it's gone.


Integrating with Rork Max Projects

Open the Rork Max project in Xcode and choose File → Add Package Dependencies → Add Local…, then pick the package folder:

/Users/masaki/Developer/DoliceUIKit

As a local package, edits to the library show up in the next build of the app. For production, push it to a repository and pin by version tag:

.package(
    url: "https://github.com/dolice/DoliceUIKit.git",
    from: "1.0.0"
)

Once it's wired in, add a line to your Rork Max prompts so new screens don't reinvent the pieces:

This project imports DoliceUIKit (ContentCard, DolicePressEffect, Animation.doliceSpring, etc.).
Don't write new cards or buttons; use these. Read colors and fonts from @Environment(\.appTheme).

When generated code comes back, ask one question: does this already exist in DoliceUIKit? If yes, swap it in. If not, decide whether it belongs in the library.

For tightening generated code further, see 10 Refactoring Patterns for Rork Max-Generated SwiftUI Code. On the React Native side, Turborepo Monorepo for Shared Components covers the equivalent idea.


Testing the Library

View-level unit tests are awkward in SwiftUI, so test the parts that hold logic. The version below adds a check for Color(hex:), which the first version didn't have:

// Tests/DoliceUIKitTests/ThemeTests.swift
 
import XCTest
import SwiftUI
@testable import DoliceUIKit
 
final class ThemeTests: XCTestCase {
    func testHexParsingAcceptsHashPrefix() {
        // With or without "#", the result should match
        let a = UIColor(Color(hex: "#7B68EE"))
        let b = UIColor(Color(hex: "7B68EE"))
        var (ar, ag, ab, aa): (CGFloat, CGFloat, CGFloat, CGFloat) = (0, 0, 0, 0)
        var (br, bg, bb, ba): (CGFloat, CGFloat, CGFloat, CGFloat) = (0, 0, 0, 0)
        a.getRed(&ar, green: &ag, blue: &ab, alpha: &aa)
        b.getRed(&br, green: &bg, blue: &bb, alpha: &ba)
        XCTAssertEqual(ar, br, accuracy: 0.001)
        XCTAssertEqual(ag, bg, accuracy: 0.001)
        XCTAssertEqual(ab, bb, accuracy: 0.001)
    }
 
    func testAnimationPresetsExist() {
        // Compiling is itself the check that the presets are defined
        _ = Animation.doliceSpring
        _ = Animation.doliceSnap
        _ = Animation.doliceEase
    }
}

For visual regression, swift-snapshot-testing compares rendered views against reference images and fails CI when they change unexpectedly.


Rolling Out Across Apps

Once the library settles, agree on how versions map to changes. This is the table I keep next to the repository:

Kind of changeTagBehavior in an app using .upToNextMinor(from: "1.0.0")
Bug fixv1.0.1Picked up automatically on the next package resolution
New featurev1.1.0Not automatic; each app updates on purpose
Breaking change (e.g. a new required protocol field)v2.0.0Not automatic; fix the compile errors app by app
.package(
    url: "https://github.com/dolice/DoliceUIKit.git",
    .upToNextMinor(from: "1.0.0")
)

Even when most of the theme is shared, each app's own character stays in its theme type. That balance — a shared floor of quality, a free ceiling of expression — is why AppThemeable exists.


Pitfalls from Real Usage

Previews crash without environment injection. Previews don't supply your custom environment values. Add .environment(\.appTheme, DefaultAppTheme()) to every #Preview:

#Preview {
    ContentCard {
        Text("Preview card")
            .padding()
    }
    .environment(\.appTheme, DefaultAppTheme())
}

Local paths break in CI. Xcode Cloud and GitHub Actions don't have ~/Developer/DoliceUIKit. Switch the dependency to the repository URL before pushing a branch that triggers CI; a pre-commit hook that flags local-path references catches the slips. For the wider CI picture, see CI/CD with Xcode Cloud.

Binary size. Unused code can inflate a binary. Release builds normally have DEAD_CODE_STRIPPING enabled by default, but it takes a minute to confirm it reads YES in Build Settings for a generated Rork Max project.


Starting Small

A shared library looks like overkill while you have one app. The moment you start the second, it begins paying for itself.

Migrating everything at once is how this stalls. Start with the three components you reuse most, see whether the workflow suits you, and widen the scope later. Your next step is small: pull ContentCard.swift out of one Rork Max project, load it back as a local package, and build. When you start the next app and that component is already waiting as a finished part, it's a reassuring feeling — and one I intend to keep protecting.

Share

Thank You for Reading

Rork Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • ✦Copy-paste ready implementation code
  • ✦New advanced guides published daily
  • ✦$5/mo or $10 for lifetime access
View Membership →

If you found this article helpful, a small tip ($1.50) would mean a lot to us. Your support helps keep this site ad-free and covers server and hosting costs.

Related Articles

⬡ Dev Tools2026-07-18
The Generated Screen That Quietly Jams at AX5 and in German — Putting Layout Resilience Checks on Rork Max SwiftUI
A record of running every Rork Max generated SwiftUI screen through pseudolocalization and the largest text size to find exactly where it jams. Covers when to reach for ViewThatFits, ScaledMetric and layoutPriority, plus the snapshot checks that catch regressions every time you regenerate.
⬡ Dev Tools2026-05-17
Reading Rork Max's SwiftUI Generation Through a Wallpaper App's Requirements — What to Trust, What to Fix, What to Write by Hand
Typical wallpaper-app requirements — grid, pinch-zoom, slideshow, photo-library permission, ads, in-app purchase — handed to Rork Max's SwiftUI generation: where the output tends to hold up and where it tends to break. For the memory failure that bites first, this note includes decode-time downsampling, a bounded cache, and a procedure for measuring on your own device.
⬡ Dev Tools2026-05-16
Migrating Firebase CocoaPods to SPM in Rork Max Apps
Since Firebase 13.0.0 (October 7, 2026) the Apple SDK ships only through Swift Package Manager and binaries, and CocoaPods trunk stops accepting podspecs on December 2. A migration log from moving Rork Max iOS apps to SPM, with a symptom-by-symptom troubleshooting table, the dSYM and Dropbox pitfalls, and what to check before moving to Firebase 13.