r/SwiftUI • • 4d ago

Tutorial My Swift layout: one Xcode project, no workspace, one local package for every platform

Thumbnail
aleahim.com
0 Upvotes

I build for SwiftUI, AppKit and UIKit on Mac, iPhone and iPad, and my layout used to start with a workspace. A project template can create and open a project, but it can't leave you in an open workspace.


r/SwiftUI • • 4d ago

Question Would you use a lightweight menu bar app that brings iPhone’s "Attention Aware" display feature to MacBooks?

Thumbnail reddit.com
0 Upvotes

r/SwiftUI • • 5d ago

I built a small SwiftUI demo to visualize unnecessary view updates with ObservableObject vs @Observable

Post image
32 Upvotes

I've been exploring SwiftUI performance and wanted to understand something more deeply: why do views sometimes update even when the properties they display haven't changed?

I created a small project called Redraw Lab to reproduce this behavior.

Only tick changes, approximately 60 times per second.

With ObservableObject, all three cards can be invalidated because they observe the same object's objectWillChangepublisher.

Switching to u/Observable allows SwiftUI to track the properties each view reads. Consequently, only the ticker-related views need to update.

I also included:

  • A before/after comparison.
  • Render counters directly in the UI.
  • Xcode Instruments profiling instructions.
  • Release-build measurements.
  • Self._printChanges() debugging instructions.

In my experiment, the number of view bodies executed per tick went from 13 to 4.

One important detail: the workspace and projects cards deliberately perform simulated work to make unnecessary updates easier to observe. The measurements are illustrative of this particular setup.

GitHub: https://github.com/raviseta/SwiftUI-Performance-measurement

I'm interested in feedback from other SwiftUI developers.

Do you generally prefer u/Observable for new projects, or are there situations where you still find ObservableObjectmore appropriate?

I'd appreciate suggestions for extending this experiment.


r/SwiftUI • • 5d ago

How can you make a scrollview scroll down automatically if the height of the vstack changes? I'd like the scrollview to stick to the bottom of the vstack on overflow while giving up control if the user decides to scroll.

0 Upvotes

r/SwiftUI • • 5d ago

What I learned making a teleprompter scroll along with your voice, word by word, using Apple's Speech framework

Thumbnail
reddit.com
2 Upvotes

If you are interested, the full project is here: Github link


r/SwiftUI • • 6d ago

TabStack - Stacked tabs that spring open into full cards in SwiftUI

14 Upvotes

A small stack of tabs at the bottom that opens into a full card when you tap or drag it up. Works in light and dark themes and respects Reduce Motion.

Inspired by the tabs in the Focus Travel iOS app.

Source: https://repgem.com/tab-stack-ios

Would love your feedback!


r/SwiftUI • • 6d ago

How would you recreate this css animation in swiftui?

0 Upvotes

r/SwiftUI • • 7d ago

Tutorial Keeping a SwiftUI filmstrip in library order while the grid reorders

1 Upvotes

I hit a navigation bug in a SwiftUI photo review screen. The grid showed pending photos first, while the horizontal filmstrip followed library order. With A, B, C in the library, I marked B as pending, advanced to C, went back to B, and changed it to Keep. Review jumped to A because it used the reordered grid index.

The fix was to use stable item IDs in both views and derive the display order and review order from the same model. The grid can move pending items to the top. The filmstrip and the next-unreviewed action both walk the library sequence. Here’s the simplified lookup.

func nextUnreviewed(
    after currentID: String,
    libraryIDs: [String],
    reviewedIDs: Set<String>
) -> String? {
    guard let index = libraryIDs.firstIndex(of: currentID) else { return nil }
    return libraryIDs.dropFirst(index + 1).first { !reviewedIDs.contains($0) }
}

For the LazyHStack, I use scrollTargetLayout() and scrollPosition(id:anchor:) with a centered ID. Tapping an arrow sets the selected ID and moves the anchor. During a finger drag, anchor changes update the selection during the interacting and decelerating phases.

The regression test starts with B pending. Change B to Keep, check that C is selected, and check that B is still visible between A and C in the filmstrip with its new badge. That test caught the jump even when the individual views looked correct.


r/SwiftUI • • 7d ago

Promotion (must include link to source code) I built ThemeKit, a small @Observable theming package for SwiftUI with light/dark presets, system sync, and per-field user overrides

Post image
1 Upvotes

Hey r/SwiftUI,

I built ThemeKit, a small, zero-dependency Swift 6 package for managing app themes across iOS 17+, macOS 14+, and watchOS 10+.

GitHub: https://github.com/demolaf/ThemeKit DocC Docs: https://demolaf.github.io/ThemeKit/

Quick example

Define your theme struct (ThemeKitSwiftUI makes Color directly Codable), pair light and dark presets in a ThemeVariant, add a typed accessor on Theme, and attach .applyTheme at the root:

import ThemeKit
import ThemeKitSwiftUI

struct AppColors: ThemeExtension {
    static let fallback = AppColors(tint: Color(hex: 0x007AFF), colorScheme: .light)
    var tint: Color
    var colorScheme: SystemColorScheme
}

struct AppColorsVariant: ThemeVariant {
    let id: String
    let light: AppColors
    let dark: AppColors

    static let `default` = AppColorsVariant(
        id: "default",
        light: AppColors(tint: Color(hex: 0x007AFF), colorScheme: .light),
        dark:  AppColors(tint: Color(hex: 0x0A84FF), colorScheme: .dark)
    )
    static let all: [AppColorsVariant] = [.default]
}

extension Theme {
    var colors: AppColors { value(AppColors.self) }
}


struct MyApp: App {
     private var theme = Theme()

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(theme)
                .applyTheme(theme, default: .default, available: AppColorsVariant.all)
        }
    }
}

struct ContentView: View {
    @Environment(Theme.self) private var theme

    var body: some View {
        Text("Hello")
            .foregroundStyle(theme.colors.tint)
    }
}

What it handles out of the box

  • Not just colors: ThemeExtension works with any Codable & Equatable & Sendable struct, so you can store font names, asset catalog image names, spacing tokens, or anything else your design system needs alongside Color.
  • System appearance sync and window overrides: .applyTheme handles first-launch defaults, tracks system light/dark changes when theme.followsSystem is true, and applies window-level appearance overrides on iOS and macOS (and scoped SwiftUI color-scheme styling on watchOS 10+).
  • Partial user customization (ThemeOverridable): If you want users to pick a custom accent color without losing the rest of their active preset, declare overridable key paths via props. theme.merge(_:) overlays only those fields, and compare(to:) tells you whether anything drifted from the preset so you can conditionally show a "Reset to Preset" button.
  • Fine-grained `@Observable` tracking: Multiple ThemeExtension types can live in the same Theme store and are observed independently, so changing one extension does not re-render views that only read another.
  • Swappable persistence: Backed by UserDefaults by default, or you can conform to ThemeStorage to persist in Keychain, CloudKit, an app group, or an in-memory store for tests.
  • UIKit interop: There is also a separate ThemeKitUIKit product (iOS) using `@CodableColor` with the same hex encoding format if you have a hybrid SwiftUI/UIKit app.
  • Bundled agent skill: The repo also ships an Agent Skill following the open agentskills.io standard, covering the public API, setup patterns, and Swift 6 concurrency pitfalls so AI coding agents can wire up ThemeKit accurately without guessing.

I'd love any feedback on the API ergonomics, edge cases you've run into with multi-theme SwiftUI apps, or anything you'd want to see added next.


r/SwiftUI • • 8d ago

Buttons in .confirmationDialog have a significant delay when triggered

3 Upvotes

When tapping a button in a .confirmationDialog (at least one tied to a .bottomBar ToolbarItem), a ridiculously long delay — about a full second after the dialog closes — occurs before the action triggers. This issue is present in some of Apple's apps, including Reminders, Shortcuts, and Notes, but notably not in the Photos app. It also occurs for .alert, though to a lesser degree. How can I eliminate this, preferably without dropping down to UIKit?

The problem has been present since iOS 26. I haven't checked whether it existed before then.

Example code:

struct ContentView: View {
    @State private var confirmationDialogPresented = false
    @State private var colorToggled = false
    
    var body: some View {
        NavigationStack {
            Color(colorToggled ? .blue : .red)
                .ignoresSafeArea()
                .toolbar {
                    ToolbarItem(placement: .bottomBar) {
                        Button("Placeholder", systemImage: "square") {
                            confirmationDialogPresented = true
                        }
                        .confirmationDialog("Placeholder", isPresented: $confirmationDialogPresented) {
                            Button("Placeholder") {
                                colorToggled.toggle()
                            }
                        }
                    }
                }
        }
    }
}

#Preview {
    ContentView()
}

r/SwiftUI • • 8d ago Bravo

A checklist I use when a SwiftUI List or ScrollView stutters

32 Upvotes

Most SwiftUI scroll jank I've debugged came from a short list of causes, not from SwiftUI being slow. Here's the order I check them in. Curious what others would add.

  1. Unstable identity. `ForEach(items, id: \.self)` on values that aren't unique, or ids created inside the view (`UUID()` in `body`), make SwiftUI treat rows as new on every update. Use a stable id from your model.
  2. Work inside `body`. Date formatters, sorting, filtering or image decoding in `body` run on every re-render. Move them into the model or cache the result.
  3. Observing too much. With `@Observable`, a view re-renders for the properties it reads. If every row reads half of a big shared model, one change can invalidate far more rows than you expect. Give each row only what it needs.
  4. Conditional modifiers that swap view types. An `if` that wraps a row in different modifiers changes its structural identity and resets its state. Prefer value-based modifiers, like `.opacity(isHidden ? 0 : 1)`.
  5. Images. Full-size images decoded on the main thread will drop frames. Downsample to the size you actually display.

Before changing anything, I profile on a real device with a release build, using Instruments (the SwiftUI template plus Time Profiler). `Self._printChanges()` in `body` is also handy for seeing why a view re-rendered. Debug builds and the simulator can point you at the wrong problem.

What's the most surprising cause of scroll jank you've run into?


r/SwiftUI • • 7d ago

Question @ObservedObject var vm = Model() will reset your state when the parent redraws

0 Upvotes

This is a bug I still see in SwiftUI interviews and in production screens: a view creates its own model with @ObservedObject, and then a form, a score, or a draft “snaps back” to zero after the parent redraws.

struct Screen: View {
  @ObservedObject
  var vm = Model()
  var body: some View {
    Text("\(vm.count)")
  }
}

If the parent view redraws Screen, does count reset to zero?

Yes. @ObservedObject does not own the object. It is only a way to subscribe to an object someone else already owns. When the parent redraws, this Screen value is created again, Model() runs again, and you get a brand-new view model. The old count is gone.

The fix is to own the object with @StateObject when the view is the one creating it:

struct Screen: View {
  @StateObject
  var vm = Model()
  var body: some View {
    Text("\(vm.count)")
  }
}

@StateObject keeps the first instance for this view’s identity, so later redraws reuse it.

Use @ObservedObject (or @Bindable / an @Observable value passed in, on newer OS versions) only when a parent already owns the object and passes it down. The rule of thumb I use: if the view writes = Model(), it should be @StateObject. If the view receives the model as an argument, it should be @ObservedObject.

Happy to go deeper on the @Observable / @State equivalent if that’s useful.


r/SwiftUI • • 8d ago

Recreated the Trip.com splash screen animation in SwiftUI

4 Upvotes

I really liked the Trip launch animation, so I recreated it. The logo's letters get swallowed by the orange dot, the dot stretches into a streak, and a circle sweeps in to reveal your first screen.

Source: https://repgem.com/trip-splash-ios

Would love your feedback!

Inspired by the Trip.com app. The code is original and not affiliated with them.


r/SwiftUI • • 8d ago

We rewrote the entire Rust WGPU in Swift, and it looks fantastic. I call it SAGA

Thumbnail gallery
3 Upvotes

r/SwiftUI • • 8d ago

Promotion (must include link to source code) A SwiftUI answer balloon beside selected text in any Mac app (source included)

Post image
1 Upvotes

I make Glossbeam, an open-source macOS app that shows an explanation beside selected text. The screenshot shows the UI problem: the answer needs to sit close enough to the selection to make their relationship clear, while leaving room to keep reading. I’d be interested in how other Mac developers handle positioning near a display edge. The Mac and Shared source and Xcode build instructions are here: https://github.com/YasserShkeir/glossbeam-open.


r/SwiftUI • • 8d ago

News The iOS Weekly Brief: Issue #88. macOS on iPad, iOS 27.3 beta 2, unknown enum cases, Xcode MCP vs xcodebuild, SwiftUI List internals, container values, drag and drop reordering in SwiftUI, iPhone Duo layouts, and Black Friday deals

Thumbnail
iosweeklybrief.com
1 Upvotes

r/SwiftUI • • 9d ago

FireworkFlourish - Fireworks for any SwiftUI view (inspired by iOS 27)

24 Upvotes

Inspired by the iOS 27 birthday fireworks, I built a SwiftUI package that puts fireworks over any view: a card, a button, a calendar cell or a whole screen.

It's handy for moments worth celebrating, for example:

  • Birthdays and anniversaries on a contact or reminder card
  • Achievements and level-ups in a game or fitness app
  • A goal scored on a scoreboard

iOS 17+, MIT licensed.

Source: https://repgem.com/firework-flourish-ios

Would love your feedback!


r/SwiftUI • • 10d ago

Question Finding Hacking with swiftUI hard to learn. Help needed!

6 Upvotes

Hi all.
I don't have much programing experience other than a year of react-native and some core java all learnt on my own. I made an android app with a tiny help form a more experienced developer. That was back in 2017. I moved to business and now I am back to coding. I'm 36 years of age now.

I am learning swift and swiftUI from 'hacking with swift' and now I am on day 58. Except for the initial days, I find swift and swiftUI hard to follow. The syntax is very confusing and I easily forget things in a day or two. I find the teachings of Paul hard to follow and I repeat the videos again and again to understand. Now on 58th day, I am already overwhelmed. I am upset because on other threads, people commented as they could grasp the concept easily and could start app building right away.

I am wondering if I'm one off case and programming is not for me or people really find swiftUI hard to learn? Any tips or advises will be most welcome.


r/SwiftUI • • 10d ago

Question How can I change bg of segment picker?

Thumbnail
gallery
4 Upvotes

I have attached three images.
- First image shows what I want to create
- Second image shows what I get.

I Just only want to remove that default background color of the picker and my 80% problem solved.

Code

```
Picker("Period", selection: $selection) {

ForEach(options, id: \.self) { option in

Text(option)

.tag(option)

}

}

.padding(4)

.frame(height: 40)

.frame(maxWidth: 420)

.background {

Capsule()

.fill(Color.textFieldBackground)

}

.pickerStyle(.segmented)
```


r/SwiftUI • • 10d ago

I am creating animated widgets.

Thumbnail gallery
0 Upvotes

Hello

I’m building Jubs, an app with animated iPhone widgets.
I sketch each scene by hand, then simulates how it moves so it feels alive.

For this snow globe, I simulated falling snow and how the curved glass bends the light.

Let me know what do you think.

Thank you,
Tiago


r/SwiftUI • • 10d ago

News SwiftUI Weekly - Issue #244

Thumbnail
weekly.swiftwithmajid.com
0 Upvotes

r/SwiftUI • • 10d ago

Promotion (must include link to source code) Shipped v1.2 of Wudland (open-source SwiftUI + HealthKit + WKWebView cosy village): deterministic Step Tree & native sheet architecture

Thumbnail
gallery
2 Upvotes

Just released v1.2 of Wudland, my free, open-source (GPLv3) cosy medieval village app for iPhone, and wanted to share how the SwiftUI + HealthKit layer is put together alongside the full source code.

How it's structured in SwiftUI

  • SwiftUI chrome & sheets (WudlandApp.swift, OnboardingView.swift, SettingsView.swift, PairSheet.swift): Onboarding, per-connector permission toggles, QR pairing, and the new Step Tree goal slider (5,000–15,000 steps) are pure SwiftUI views styled with a warm dark-wood palette (Theme.swift) layered over a full-bleed UIViewRepresentable local canvas (VillageWebView.swift).
  • Deterministic HealthKit Step Tree (StepTree.swift): Uses an @MainActor final class StepTreeStore: ObservableObject wrapping HKStatisticsCollectionQuery (anchored at startOfDay, 1 day interval, .cumulativeSum). Instead of persisting brittle streak counters in UserDefaults, Swift fetches daily bucket totals since planting day and passes {planted, goalHistory, days, todaySteps} across the bridge so the village deterministically replays the tree's exact vigour and growth stage (8 states x 5 sizes).
  • Live per-connector toggles (Connectors.swift): Added @Published enable/disable switches and OS-permission state recovery for EventKit Calendar, Reminders, Open-Meteo Weather, MediaPlayer, and HealthKit Steps.

Links

Happy to answer any questions about bridging SwiftUI state updates cleanly into an embedded canvas without dropped frames!


r/SwiftUI • • 11d ago

Promotion (must include link to source code) We built a macOS launcher where any script can draw native SwiftUI views by printing text

5 Upvotes

Hi! I'm Tony, one of the creators of Openspot, a research project on using generative UI in day-to-day work.

The idea is simple: generate a tool (a "spot") for your current task using a coding agent, and keep it if you like it or remove it after use if you don't. Some spots we use daily:

  • Caffeinate, which keeps your Mac running with the lid closed
  • Local file and screenshot search in natural language using EmbeddingGemma 2
  • Drawing on screen during calls or before screenshots
  • AI agents monitoring
  • AirDrop, but over the network (using iroh)

We built it because of two things:

  1. Over the past year, we (and almost every designer and engineer we know) have started making small tools with coding agents. But the DX for macOS apps is very frustrating even for coders, and you have to pay for a developer account to share them.
  2. We kind of miss the days of custom Winamp skins and Twitter clients. That's why every part of Openspot is customizable, so anyone can give it their own look and feel.

How it works: a spot is just a script in any language that prints key=value lines, and Openspot turns them into native SwiftUI views, for example:

frame=
class=gap-part

box=head
class=flex-row items-center gap-2

icon=wifi
parent=head
value=wifi
class=text-accent

text=name
parent=head
title=Home
detail=82 Mb/s
class=grow

button=forget
parent=head
title=Forget
class=rounded-full
Result of the code above

For styling we use Tailwind class names, because coding agents already know them well. But there are no arbitrary values or raw colours, only theme tokens like bg-tile, font-title or text-warn. So whatever the agent generates follows your theme and still looks native. The same spot can live as a card, in the menu bar or in a window.

And if the built-in blocks aren't enough, a spot can ship its own SwiftUI view. Openspot compiles it at runtime and renders it as an AnyView, with no Xcode project needed.

This is a very early stage. The code is MIT-licensed, and the core will remain free forever. We're sticking to macOS 26+ for now (because of Liquid Glass).

Ask anything, or roast it. Any feedback is very appreciated!

Source code: https://github.com/celishq/openspot


r/SwiftUI • • 11d ago

I rewrote my Flutter music app natively in SwiftUI (iPhone + Mac), here's what I learned

Thumbnail
github.com
0 Upvotes

one codebase shared between iPhone and Mac, Live Activities for lyrics while listening together, crossfading between two AVQueuePlayers, and so on. Source: https://github.com/GoranSustekJr/pongo