Provide views, controls, and layout structures for declaring your app's user interface using SwiftUI.

Posts under SwiftUI tag

200 Posts

Post

Replies

Boosts

Views

Activity

Animating items between a VStack and a ZStack?
Hey there! I'd love to know if theres a way where you can animate items between ZStack and VStacks? Just like the native iOS notifications on the Lockscreen stack at the bottom and if tapped, they convert from a Stack to a List - I have a list with items, displayed in a VStack, and I make the list collapsable when swiping down, where the items stack behind eachother with a progresisve reduction in opacity & scale, but I havent figured out a way to animate the items between the list and the stack - where you can visually see items starting to overlap and stack ontop of eachother when collapsing the list.
0
0
119
May ’25
Live activity widget not updated locally after server update
I am using live activity in my app. Functionality is start, update & end events are started from the server. There is one interaction button added using app intent in live activity widget. That button needs to update widget ui locally using activity kit. Issue is when os receives first start event push then update ui works fine and reflecting on live activity widget but when update notification receives by os after 1 mins then action button stops updating the ui locally. Can anyone please add some suggestions to fix this.
0
0
110
May ’25
Clearing an app’s memory, data etc.
My app works perfectly the first time it is used but when returning to the start after playing the game and playing another it does some random things. I figure it is because the app still retains the previous game in it’s memory allocation? My question is, what is the best way programmatically to have an app start fresh and not have to quit it and open it again?
6
0
133
May ’25
Combining NavigationSplitView and TabView in iOS 18
Hi folks, I've used a NavigationSplitView within one of the tabs of my app since iOS 16, but with the new styling in iOS 18 the toolbar region looks odd. In other tabs using e.g. simple stacks, the toolbar buttons are horizontally in line with the new tab picker, but with NavigationSplitView, the toolbar leaves a lot of empty space at the top (see below). Is there anything I can do to adjust this, or alternatively, continue to use the old style? Thanks!
11
3
2.6k
May ’25
SubscriptionStoreView not showing free trial offer in release build
I'm using the SwiftUI view SubscriptionStoreView (https://developer.apple.com/documentation/storekit/subscriptionstoreview/) with a subscription group that has 2 subscriptions. I set up a free trial offer in App Store Connect (https://developer.apple.com/help/app-store-connect/manage-subscriptions/set-up-introductory-offers-for-auto-renewable-subscriptions/). The storekit file in Xcode is synced with the App Store. In debug build, this works and appears correctly, showing the free trial offer: But in release build, the free trial offer is not shown: The code is very simple: SubscriptionStoreView(productIDs: [ "[PRODUCT ID FOR ANNUAL SUBSCRIPTION]", "[PRODUCT ID FOR BIMONTHLY SUBSCRIPTION]" ]) Does anyone have a solution? Thank you. (Xcode 16.3, macOS 15.5, iOS 18.5)
0
0
73
May ’25
SwiftUI Full keyboard access doesn't navigate through every button on screen
I have screen in my app that can represented by following layout, I would like this screen to be possible to navigate with full keyboard access but there is unexpected behavior: Path: Tap "Tab" on keyboard -> whole scrollview is targeted and inside the first button1 is selected. Arrow down -> selection changes to button3 Arrow up -> selection changes back to button1 So button2 is always skipped, there is no way to navigate to it by arrows left/right. Using Tab+F and searching "button2", button2 is correctly selected, so it's selectable but for some reason not findable by going through elements. Putting empty text in Text views cause buttons to be vertically aligned and then everything works correctly but it is not an option. public struct BugReportView: View { public var body: some View { ScrollView { VStack(spacing: .zero) { Button("button1", action: { }) HStack { Text("some text") Text("some text2") Button("button2", action: { }) } Button("button3", action: { }) } } } }
0
3
148
May ’25
Design Challenges with persistent toast message
I have an ongoing activity in progress. Think of: a delivery in progress house internet reboot in progress some water / electricity / internet / tv outage. (food) order processing I want to show a persistent toast message above the tab bar, across all tabs and screens across the app. It could take 15 minutes until the activity is finished. Obviously there's a challenge of: accessibility content overlaying with each other extra engineering effort. What we've thought of doing is: Option1: show a toast message, but when a modal is presented then it presents on top of the toast message. The toast message no longer updates itself. Once the modal is finished, then the toast message re-appears and continues to update. Option2: keep the toast message across all tabs and modals and work through the challenges mentioned Question: What are some other design approaches that could be taken to persist an ongoing activity (much like 'Live Activity', but just across the app when it's in foreground) or what are some design reasons that the two options considered are bad?
0
0
169
May ’25
onDrop() modifier with multiple UTTypes giving the least helpful one?
Hey folks I'm trying to use .onDrop() on a view that needs to accept files. This works fine, I specify a supportedContentTypes of [.fileURL] and it works great. I got a request to add support for dragging the macOS screenshot previews into my app and when I looked at it, they aren't available as a URL, only an image, so I changed my array to [.fileURL, .image]. As soon as I did that, I noticed that dragging any image file, even from Finder, calls my onDrop() closure with an NSItemProvider that only knows how to give me an image, with no suggestedName. Am I missing something here? I had been under the impression that: The order of my supportedContentTypes indicates which types I prefer (although I now can't find this documented anywhere) Where an item could potentially vend multiple UTTypes, the resulting NSItemProvider would offer up the union of types that both it, and I, support. If it helps, I put together a little test app which lets you select which UTTypes are in supportedContentTypes and then when a file is dragged onto it, it'll tell you which content types are available - as far as I can tell, it's only ever one, and macOS strongly prefers to send me an image vs a URL. Is there anything I can do to convince it otherwise?
4
0
151
May ’25
Crash due to likely infinitely recursive call in SwiftUI `Color.Resolved.init`
So I'm dealing with a really obtuse crash that appears to be a stack overflow in an internal SwiftUI code path creating a Color.Resolved. I haven't found anyone one else with this issue online, and I cannot get it to reproduce on my own device. Interestingly enough, it is only happening on 1 device in the field (according to XCode crash logs). Here are some lines from the crashed thread. You can see that my code is never called, and it appears to be starting in some Array equality check checking the equality of colors (which I can't think of anywhere in my app I am doing anyway). You can see from this trace here that it appears to be a recursive call through Color.Resolved and NSColor.withColorAppearance. I don't have any idea how to solve this, but it keeps happening with at least one in-the-field device across multiple app updates. So my whole app is open source on github at https://github.com/msdrigg/roam, but I don't even use NSColor explicitly anywhere except for here which doesn't match the stack trace. I also tried changing the accent color of the app with defaults write com.msdrigg.roam AppleAccentColor -integer 1 to see if that somehow caused the crash, but my app opened up totally fine (and respected the change). Besides this, the only places I think I could be using dynamic colors is I when define an AccentColor and a WidgetBackground color for my app using xcassets, and then I use these colors from SwiftUI. In most of my app I stick to the system colors (Color.gray and such). Thread 0 Crashed: 0 libsystem_pthread.dylib 0x000000018601213c ___chkstk_darwin + 60 1 CoreFoundation 0x0000000186108434 -[NSArray isEqualToArray:] + 52 (NSArray.m:454) 2 AppKit 0x000000018a21fcd4 -[NSCoreUICatalogColor resolvedCUINamedColorForAppearance:] + 164 (NSColor.m:5057) 3 AppKit 0x0000000189c32cd4 -[NSCoreUICatalogColor resolvedColor] + 48 (NSColor.m:5148) 4 AppKit 0x0000000189c31e74 -[NSDynamicNamedColor colorUsingColorSpace:] + 32 (NSColor.m:4410) 5 SwiftUICore 0x0000000221ca9fd8 CoreColorPlatformColorGetComponents + 116 (CoreColorFunctions.m:149) 6 SwiftUICore 0x0000000221faaf28 specialized Color.Resolved.init(platformColor:) + 92 (CoreColor.swift:14) 7 SwiftUICore 0x0000000221faa5b0 Color.Resolved.init(platformColor:) + 16 (<compiler-generated>:0) 8 SwiftUI 0x00000001b53b1dc4 closure #1 in NSColor.resolve(in:) + 20 (AppKitColorConversions.swift:156) 9 SwiftUI 0x00000001b53b222c partial apply for closure #1 in static NSColor.withColorAppearance(in:_:) + 32 (<compiler-generated>:0) 10 SwiftUI 0x00000001b46b1e54 closure #1 in SubmitTriggerSource.dispatchUpdate(_:) + 28 (PlatformViewCoordinator.swift:12) 11 SwiftUI 0x00000001b5484488 thunk for @escaping @callee_guaranteed () -> () + 28 (<compiler-generated>:0) 12 AppKit 0x0000000189c174a4 +[NSAppearance _performWithCurrentAppearance:usingBlock:] + 72 (NSAppearance.m:2408) 13 SwiftUI 0x00000001b53b2088 specialized static NSColor.withColorAppearance(in:_:) + 324 (AppKitColorConversions.swift:142) 14 SwiftUI 0x00000001b53b1e7c protocol witness for ColorProvider.resolve(in:) in conformance NSColor + 68 (<compiler-generated>:151) 15 SwiftUICore 0x0000000222436e6c ColorBox.resolve(in:) + 124 (Color.swift:288) 16 SwiftUICore 0x0000000222435e30 Color.resolve(in:) + 72 (Color.swift:87) 17 SwiftUI 0x00000001b53b1c88 closure #1 in NSColor.init(_:) + 196 (AppKitColorConversions.swift:124) 18 SwiftUI 0x00000001b4542714 thunk for @escaping @callee_guaranteed (@guaranteed NSAppearance) -> (@owned NSColor) + 56 (<compiler-generated>:0) 19 AppKit 0x0000000189c31e74 -[NSDynamicNamedColor colorUsingColorSpace:] + 32 (NSColor.m:4410) //// ... Repeating for 500 lines 500 SwiftUICore 0x0000000221ca9fd8 CoreColorPlatformColorGetComponents + 116 (CoreColorFunctions.m:149) 501 SwiftUICore 0x0000000221faaf28 specialized Color.Resolved.init(platformColor:) + 92 (CoreColor.swift:14) 502 SwiftUICore 0x0000000221faa5b0 Color.Resolved.init(platformColor:) + 16 (<compiler-generated>:0) 503 SwiftUI 0x00000001b53b1dc4 closure #1 in NSColor.resolve(in:) + 20 (AppKitColorConversions.swift:156) 504 SwiftUI 0x00000001b53b222c partial apply for closure #1 in static NSColor.withColorAppearance(in:_:) + 32 (<compiler-generated>:0) 505 SwiftUI 0x00000001b46b1e54 closure #1 in SubmitTriggerSource.dispatchUpdate(_:) + 28 (PlatformViewCoordinator.swift:12) 506 SwiftUI 0x00000001b5484488 thunk for @escaping @callee_guaranteed () -> () + 28 (<compiler-generated>:0) 507 AppKit 0x0000000189c174a4 +[NSAppearance _performWithCurrentAppearance:usingBlock:] + 72 (NSAppearance.m:2408) 508 SwiftUI 0x00000001b53b2088 specialized static NSColor.withColorAppearance(in:_:) + 324 (AppKitColorConversions.swift:142) 509 SwiftUI 0x00000001b53b1e7c protocol witness for ColorProvider.resolve(in:) in conformance NSColor + 68 (<compiler-generated>:151) 510 SwiftUICore 0x0000000222436e6c ColorBox.resolve(in:) + 124 (Color.swift:288) full-log.crash
0
0
77
May ’25
visionOS NavigationSplitView - Refreshable ProgressView Disappears
Description I've encountered an issue with NavigationSplitView on visionOS when using a refreshable ScrollView or List in the detail view. The Problem: When implementing pull-to-refresh in the detail view of a NavigationSplitView, the ProgressView disappears and generates this warning: Trying to convert coordinates between views that are in different UIWindows, which isn't supported. Use convertPoint:fromCoordinateSpace: instead. I discovered that if the detail view includes a .navigationTitle(), the ProgressView remains visible and works correctly! Below is a minimal reproducible example showing this behavior. When you run this code, you'll notice: The sidebar refreshable works fine The detail refreshable works only when .navigationTitle("Something") is present Remove the navigationTitle and the detail view's refresh indicator disappears minimal Demo import SwiftUI struct MinimalRefreshableDemo: View { @State private var items = ["Item 1", "Item 2", "Item 3"] @State private var detailItems = ["Detail 1", "Detail 2", "Detail 3"] @State private var selectedItem: String? = "Item 1" var body: some View { NavigationSplitView { List(items, id: \.self, selection: $selectedItem) { item in Text(item) } .refreshable { items = ["Item 1", "Item 2", "Item 3"] } .navigationTitle("Chat") } detail: { List { ForEach(detailItems, id: \.self) { item in Text(item) .frame(height: 100) .frame(maxWidth: .infinity) } } .refreshable { detailItems = ["Detail 1", "Detail 2", "Detail 3"] } .navigationTitle("Something") } } } #Preview { MinimalRefreshableDemo() } Is this expected behavior? Has anyone else encountered this issue or found a solution that doesn't require adding a navigation title?
1
0
60
May ’25
SwiftUI List - onInsert not called on iOS (works on macOS)
I am working with a simple SwiftUI List and I want to enable functionality that allows files and images to be dropped onto the List from outside the app. There is an onInsert modifier with List that allows for this, but I found that it works on macOS, but not when running the same view on iOS. I have sample code that I can't seem to post on this forum because it keeps giving me a validation error about "This post contains sensitive language". Maybe this will work: Code to reproduce issue Is there anything I can do to make this work on iOS?
1
0
84
May ’25
[StoreKit] Runtime warning with manageSubscriptionsSheet and ObservableObject
The following runtime warning is emitted by Xcode when using the manageSubscriptionsSheet with an ObservableObject: \ContentViewModel.isPresented is isolated to the main actor. Accessing it via Binding from a different actor will cause undefined behaviors, and potential data races; This warning will become a runtime crash in a future version of SwiftUI. Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive(on:)) on model updates. This minimal sample project reproduces the issue: class ContentViewModel: ObservableObject { @Published var isPresented = false func didTapButton() { self.isPresented = true } } struct ContentView: View { @ObservedObject var viewModel: ContentViewModel var body: some View { Button("Tap me") { self.viewModel.didTapButton() } .manageSubscriptionsSheet(isPresented: self.$viewModel.isPresented) } } Reproduced on: Xcode 16.2 Xcode 16.3 beta both with a simulator and a real device. This doesn't happen when using @Observable.
1
1
226
May ’25
onContinueUserActivity(CSSearchableItemActionType, perform) does not work on a SwiftUI macOS app
onContinueUserActivity(CSSearchableItemActionType, perform) works as expected on iOS when we search and select an item from Spotlight, but nothing happens when we do the same on a SwiftUI macOS app. var body: some Scene { WindowGroup { MyView() .onContinueUserActivity(CSSearchableItemActionType, perform: handleSpotlight) } } func handleSpotlight(_ userActivity: NSUserActivity) { // Is not called... } How can we respond to a user clicking a Spotlight result from our apps on macOS?
2
1
771
May ’25
iOS Dynamically loaded custom fonts in WidgetKit not working on real device (simulator is fine). Sandbox chronod deny file-read-data for font file.
Project structure is: App target + widget extension + widget intent extension All share a common appgroup group.com.x.y and all file handling is done using FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.x.y") so that only the shared container is used. Using the Main app target, a font "Chewy-Regular.ttf" is downloaded and saved to the shared AppGroup container. Font can now be loaded via CTFontManagerRegisterFontsForURL and displayed in a Main App Text view Text("Testing...").font(Font.custom("Chewy-Regular", size: 20)) Now add a Widgetkit widget instance that uses this font. In 'getTimeLine() and getSnapShot() of IntentTimelineProvider we load the font again via CTFontManagerRegisterFontsForURL (this needs to happen again probably because widget runs in a separate process from the main app?). On simulator, the widget will show the correct font. BUT On iPhone7 real device, the widget will show the 'redacted placeholder view'. It seems that something is crashing. I see in the device console : error 14:39:07.567120-0800 chronod No configuration found for configured widget identifier: D9BF75EE-4A04-441A-8C85-1507F7ECE379 fault 14:39:07.625600-0800 widgetxExtension -[EXSwiftUI_Subsystem beginUsing:withBundle:] unexpectedly called multiple times. error 14:39:07.672733-0800 chronod Encountered an error reading the view archive for &amp;lt;private&amp;gt;; error: &amp;lt;private&amp;gt; error 14:39:07.672799-0800 chronod [co.appevolve.onewidget.widgetx:widgetx:small:1536744920620481560@148.0/148.0/20.2] reload: could not decode view error 14:39:07.674984-0800 kernel Sandbox: chronod(2128) deny(1) file-read-metadata /private/var/mobile/Containers/Shared/AppGroup/9B524570-1765-4C24-9E0C-15BC3982F0DC/downloadedFonts/Chewy/Chewy-Regular.ttf error 14:39:07.675762-0800 kernel Sandbox: chronod(2128) deny(1) file-read-data /private/var/mobile/Containers/Shared/AppGroup/9B524570-1765-4C24-9E0C-15BC3982F0DC/downloadedFonts/Chewy/Chewy-Regular.ttf error 14:39:07.708914-0800 chronod [u 8D2C83B3-A6CB-432E-A9D4-9BC8F7056B10:m (null)] [&amp;lt;private&amp;gt;(&amp;lt;private&amp;gt;)] Connection to plugin invalidated while in use. fault 14:39:07.710284-0800 widgetxExtension -[EXSwiftUI_Subsystem beginUsing:withBundle:] unexpectedly called multiple times. error 14:39:07.803468-0800 chronod Encountered an error reading the view archive for &amp;lt;private&amp;gt;; error: &amp;lt;private&amp;gt; It seems that it's a permission issue, and the textview can't access the font file it needs when the widget is rendering. Notes: 1) Font is definitely registered because I can see them in for fontFamily in UIFont.familyNames {             for fontName in UIFont.fontNames(forFamilyName: fontFamily) {                 print(fontName) &amp;amp;#9;&amp;amp;#9;&amp;amp;#9;&amp;amp;#9;&amp;amp;#9;&amp;amp;#9;&amp;amp;#9;&amp;amp;#9;... in both the Main App target and the Widget Extension target 2) If I make make the font part of the app bundle and add to 'Fonts provided by application' , the are loaded absolutely fine in the Main App and the Widget on simulator and iPhone 7 real device. 3) I do see this error sometimes in the Widget extension target log, don't know if it's related. widgetxExtension[1385:254599] [User Defaults] Couldn't read values in CFPrefsPlistSource&amp;lt;0x28375b880&amp;gt; (Domain: group.co.appevolve.onewidget, User: kCFPreferencesAnyUser, ByHost: Yes, Container: (null), Contents Need Refresh: Yes): Using kCFPreferencesAnyUser with a container is only allowed for System Containers, detaching from cfprefsd 4) I suspected something to do with app groups, so I tried to copy the font into the Widget Extension container and load from there, but had the same result. Please help! Thank you.
7
1
2.8k
May ’25
SwiftData/ModelSnapshot.swift:46: Fatal error: A ModelSnapshot must be initialized with a known-keys dictionary
I'm running into a crash when trying to delete an item from a list that's loaded using SwiftData. The app works fine when selecting or displaying the data, but the moment I confirm a deletion, it crashes with this error: SwiftData/ModelSnapshot.swift:46: Fatal error: A ModelSnapshot must be initialized with a known-keys dictionary This happens right after I delete an item from the list using modelContext.delete(). I’ve double-checked that the item exists and is valid, and I'm not sure what I'm doing wrong. The data is loaded using @Query and everything seems normal until deletion. For further information, I have tried this on a new IOS project where I have one super Model class with a cascading relationship on a child class. When trying to delete the parent class while connected to one or more children, it still gives me the error. The same thing is happening with my original project. Class A has a relationship (cascading) with Class B. Attempting to delete Class A while there are relationships with Class B throws this error. If anyone has experienced this or knows what causes it, please let me know. I’m not even sure where to start debugging this one. Thanks in advance!
2
1
172
May ’25
ARView rotation animation changes when coming back to it from a navigationLink
I have an app that uses RealityKit and ARKit, which includes some capturing features (to capture and image with added Entities). I have a navigationLink that allows the user to see the gallery of the images he has taken. When launching the App, the rotation animation of the ARView happens smoothly, the navigationBar transitions from one orientation to another with the ARView keeping it's orientation. However, when I go to the galeryView to see the images and go back to the root view where the ARView is, the rotation animation of the ARView changed: When transitioning from one orientation to another, the ARView is flipped by 90° before transitioning to the new orientation. The issue is shown in this gif (https://i.stack.imgur.com/IOvCx.gif) Any idea why this happens and how I could resolve it without locking the App's orientation changes? Thanks!
1
0
768
May ’25
Xcode Resets the Canvas (Preview) Window
Hello, In the recent update i installed of Mac and Xcode. After working out the initial problem of Simulator runtimes not found, I created a new project with new problem where When i switch to a different file, or Hide and Show Canvas again it just resets to its size (approx. 50%) of Editor. The current solution is to Pin it and it stays there with right size (No matter which file - with any extension - to switch from or to then). I tried deleting Derived Data folder, Rebooting Mac, Reintsalled Xcode (When Simulator Runtime not found problem) but the problem is there. I also tried trait property but fixedLayout do not work with iOS.
1
0
93
May ’25
Enabling Show Tab Bar Programmatically
I have a macOS application developed in SwiftUI. It's a document-based application. I know how to hide the Show Tab Bar command under View. I don't want to hide it. I always want to show tabs. I wonder how to enable this command programmatically such that the document window always has the + button to the right. Thanks.
0
0
84
May ’25
Opening FileDocument with URL → should only be called in the main thread
Its document says openDocument can open a document at a specific URL. So I've saved a model as a JSON object with its URL and a bookmark as Data. With its security-scoped bookmark data resolved, I am able to open a document except that the app will crash right after opening a document. Console says should only be called in the main thread struct ContentView: View { @EnvironmentObject var bookmarkViewModel: BookmarkViewModel var body: some View { VStack { } .onAppear { loadBookmarks() } } extension ContentView { func loadBookmarks() { print("1 \(Thread.current)") // NSMainThread Task { for bookmarkItem in bookmarkViewModel.bookmarkItems { // resolving a security-scoped bookmark print("2 \(Thread.current)") // NSMainThread if let _ = resolveBookmark(bookmarkData: bookmarkItem.bookmarkData) { print("3 \(Thread.current)") // NSMainThread do { print("4 \(Thread.current)") // NSMainThread try await openDocument(at: bookmarkItem.bookmarkURL) print("5 \(Thread.current)") // NSMainThread } catch { print("\(error.localizedDescription)") } } } } } } Well, the application is on the main thread. I've checked every line before and after opening a document with its URL. Call what on the main thread? This is confusing. Thanks. class BookmarkViewModel: ObservableObject { @Published var bookmarkItems: [BookmarkItem] = [] var defaultFileManager: FileManager { return FileManager.default } var documentURL: URL? { ... } init() { fetchBookmarkItems() } func fetchBookmarkItems() { bookmarkItems.removeAll() if let documentURL { let bookmarkFolderURL = documentURL.appending(path: "MyApp").appending(path: "Bookmarks") do { let contents = try defaultFileManager.contentsOfDirectory(atPath: bookmarkFolderURL.path) for content in contents { ... let fileURL = bookmarkFolderURL.appending(path: content) let data = try Data(contentsOf: fileURL) let bookmarkItem = try JSONDecoder().decode(BookmarkItem.self, from: data) bookmarkItems.append(bookmarkItem) } } catch { print("Error fetching folder content: \(error.localizedDescription)") } } } } struct BookmarkItem: Codable, Hashable { let bookmarkURL: URL let date: Date let bookmarkData: Data let open: Bool }
4
0
87
May ’25