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

SwiftUI Documentation

Posts under SwiftUI subtopic

Post

Replies

Boosts

Views

Activity

How do I use containerRelative on a grid in my widget?
I want to display a grid of items in my widget similar to the systemLarge Shortcuts app widget. I use clipShape(.containerRelative) to get the widget corner radius, but items that do not touch a corner in any way do not get this treatment. This is even worse with the extra large widget. How can I apply the corner radius of the widget minus the padding across all items? It does not seem like the radius is exposed outside of that special shape.
1
0
63
3w
Unable to get external display working
Trying to get my iPad app to display a different view on connected external display. Info.plist is setup as follows: <dict> <key>UIApplicationSceneManifest</key> <dict> <key>UIApplicationSupportsMultipleScenes</key> <true/> <key>UISceneConfigurations</key> <dict> <key>UIWindowSceneSessionRoleExternalDisplayNonInteractive</key> <array> <dict> <key>UISceneConfigurationName</key> <string>External Display</string> <key>UISceneDelegateClassName</key> <string>$(PRODUCT_MODULE_NAME).SceneDelegate</string> </dict> </array> </dict> </dict> </dict> I have my SceneDelegate setup as the follows: import SwiftUI class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard let windowScene = scene as? UIWindowScene else { return } if session.role == .windowExternalDisplayNonInteractive { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: ExternalDisplayView()) self.window = window window.makeKeyAndVisible() } } } I've tested running on a physical iPad with usb-c to hdmi connected and it only mirror's the screen. Same when connecting to AirPlay. Also tested running a simulator with external display enabled. Is there something I'm missing?
Topic: UI Frameworks SubTopic: SwiftUI
3
0
79
3w
StoreKit's manageSubscriptionsSheet view modifier not loading
Our app was just rejected by Apple because they say the subscription management sheet never loads. It just spins indefinitely. We're using StoreKit's manageSubscriptionsSheet view modifier to present the sheet, and it's always worked for us when testing in SandBox. Has anyone else had this problem? Given that it's Apple's own code that got us rejected, what's our path forward?
10
5
1.3k
3w
Unable to find Slider/UISlider neutralValue
An WWDC 25 a neutral value was demonstrated that allows the Slider to be 'coloured in' from the point of the neutral value to the current thumb position. Trying to use this in Dev release 1 I get errors saying no such modifier. Was this functionality released in Dev Release 1 or am I using it incorrectly?
7
2
124
4w
Properly Implementing “Open Recent” Menu for a SwiftUI non Document-Based macOS Music Player
I've already searched extensively on Apple Developer Forums and Stack Overflow, and didn't really find what I need or I missed it. I'm developing a macOS music player app that uses cuesheet files paired with audio files. The core functionality is working, opening and playing files works without issues, but I'm struggling with implementing proper file handling features due to my limited experience with UI frameworks. The current state of my app is intentionally simple: Single window interface representing a music player with track list Opening cuesheet files changes the “disc” and updates the window Built with SwiftUI (not AppKit) Not created as a Document-Based app since the user doesn't need to edit, save, or work with multiple documents simultaneously What I Need to Implement: Open Recent menu that actually works Recent files accessible from Dock menu Opening cuesheet files from Finder Drag-and-drop cuesheet files onto app window (lower priority) Problems I've Encountered: I've tried multiple approaches but never achieved full functionality. The closest I got was an “Open Recent” menu that: Only updated after app relaunch Its drop-down kept closing while music was playing My Questions Is it possible purely in SwiftUI? Is there documentation I'm missing? I feel like I might be overcomplicating this. I'm open to alternative approaches if my current direction isn't ideal: Should I redesign as Document-Based? Since I apparently need NSDocumentController, would it be better to start with a Document-Based app template and disable unwanted features, and how? Should I mix AppKit with SwiftUI? While SwiftUI has been wonderful for my main window, it's becoming frustrating for other UI parts, especially menus. Would using AppKit for menus and keeping SwiftUI for the main interface be a reasonable approach? I thought this would be straightforward: Customize the .fileImporter with the proper logic of what to do with the files Call NSDocumentController.shared.noteNewRecentDocumentURL(url) so the Open Recent menu is created a populated with opened files. Maybe it really is that simple and I've gotten lost down a rabbit hole? UI programming is quite new to me, so I might be missing something obvious. Any guidance, code examples, or pointing me toward the right documentation would be greatly appreciated!
2
0
75
4w
GCMouse causes onDisappear to not run after dismissImmersiveSpace?
I have created a simple app that enters and exits an immersive space. I have not changed the basic code that gets created when you start a new visionOS project. I have connected a Magic Mouse to the AVP using BT. I have added a simple call to print(GCMouse.mice())and I have also tried print(GCController.controllers()) when the RealityView is launched inside the body closure. If I do not have the GCMouse/GCController call, everything works fine. However, with this perfect storm (Magic Mouse connected, enter immersive space, call GCMouse/GCController, exit immersive space) the onDisappear closure is never called, so I cannot reset my ToggleImmersiveSpace button out of disabled state due to transition. Once I power off and disconnect the mouse, the onDisappear closure is finally called. I have attempted to profile the issue, and I see that right before the onDisappear is called after the controllers are disconnected (which is long after the dismissImmersiveSpace was called), I see two mentions of some deallocation/destruction of GameController: -[GCMouse.cxx_destruct] -[GCPhysicalInputProfile(Pooling) release]
2
0
87
4w
Display .icon files in SwiftUI
Is there a way to display a .icon file in SwiftUI? I want to show the app icon in the app itself but exporting and including the app icon as a PNG feels redundant. This would consume a lot of unnecessary storage especially when including a lot of alternative app icons. There has to be a better way Otherwise I would file a feedback for that Thank you
0
5
72
4w
Hide search field always
Greetings, Please type slowly, I'm new at this. iOS 18.x. Added search to a list, visibility toggled with a toolbar button, using this line of code: .searchable(text: $searchText, isPresented: $isSearchPresented, placement: .navigationBarDrawer(displayMode: .automatic), prompt: "Search...") Realized I was re-stating defaults, changed it to this: .searchable(text: $searchText, isPresented: $isSearchPresented, prompt: "Search...") In both cases, it works great when in the middle of the list, just like I wanted. However, when I scroll to the top of the list, the serach field is displayed even when 'isPresented' is false. Is there any way to keep the search field hidden even at the top of the list? ..thanks!
Topic: UI Frameworks SubTopic: SwiftUI Tags:
2
0
102
4w
Using .glassEffect in Charts
Hi, I was wondering if it's possible (and advisable) to use the new glass effects available in iOS 26 in Swift Charts? For example, in a chart like the one in the image I've attached to this post, I was looking to try adding a .glassEffect modifier to the BarMarks to see how that would look and feel. However, it seems it's not available directly on the BarMark (ChartContent) type, and I'm having trouble adding it in other ways too, such as using in on the types I supply to modifiers like foregroundStyle or clipShape. Am I missing anything? Maybe it's just not advisable or necessary to use glass effects within Charts?
5
0
180
4w
High CPU Usage in SwiftUI UIHostingController on iOS 26 Beta
Experiencing 100% CPU usage in SwiftUI app using UIHostingController, only on iOS 26 beta and Xcode beta. Issue involves excessive view updates in AttributeGraph propagation. Stack trace (main thread): thread #1, queue = 'com.apple.main-thread', stop reason = signal SIGSTOP frame #0: 0x00000001c38b9aa4 AttributeGraph`AG::Graph::propagate_dirty(AG::AttributeID) + 416 frame #1: 0x00000001d9a743ec SwiftUICore`SwiftUI.ObservationGraphMutation.apply() -> () + 656 frame #2: 0x00000001d97c0d4c SwiftUICore`function signature specialization <Arg[2] = [Closure Propagated : closure #1 () -> () in SwiftUI.(AsyncTransaction in _F9F204BD2F8DB167A76F17F3FB1B3335).apply() -> (), Argument Types : [SwiftUI.AsyncTransaction]> of generic specialization <()> of closure #1 () throws -> τ_0_0 in SwiftUI.withTransaction<τ_0_0>(SwiftUI.Transaction, () throws -> τ_0_0) throws -> τ_0_0 + 336 frame #3: 0x00000001d9a6ac80 SwiftUICore`merged function signature specialization <Arg[3] = Owned To Guaranteed> of function signature specialization <Arg[1] = [Closure Propagated : implicit closure #2 () -> () in implicit closure #1 @Sendable (SwiftUI.(AsyncTransaction in _F9F204BD2F8DB167A76F17F3FB1B3335)) -> () -> () in SwiftUI.GraphHost.flushTransactions() -> (), Argument Types : [SwiftUI.AsyncTransaction]> of SwiftUI.GraphHost.runTransaction(_: Swift.Optional<SwiftUI.Transaction>, do: () -> (), id: Swift.Optional<Swift.UInt32>) -> () + 196 frame #4: 0x00000001d9a52ab0 SwiftUICore`SwiftUI.GraphHost.flushTransactions() -> () + 176 frame #5: 0x00000001d8461aac SwiftUI`closure #1 (SwiftUI.GraphHost) -> () in SwiftUI._UIHostingView._renderForTest(interval: Swift.Double) -> () + 20 frame #6: 0x00000001d9bf3b38 SwiftUICore`partial apply forwarder for closure #1 (SwiftUI.ViewGraph) -> τ_1_0 in SwiftUI.ViewGraphRootValueUpdater.updateGraph<τ_0_0>(body: (SwiftUI.GraphHost) -> τ_1_0) -> τ_1_0 + 20 frame #7: 0x00000001d9e16dc4 SwiftUICore`SwiftUI.ViewGraphRootValueUpdater._updateViewGraph<τ_0_0>(body: (SwiftUI.ViewGraph) -> τ_1_0) -> Swift.Optional<τ_1_0> + 200 frame #8: 0x00000001d9e1546c SwiftUICore`SwiftUI.ViewGraphRootValueUpdater.updateGraph<τ_0_0>(body: (SwiftUI.GraphHost) -> τ_1_0) -> τ_1_0 + 136 frame #9: 0x00000001d8461a7c SwiftUI`closure #1 () -> () in closure #1 () -> () in closure #1 () -> () in SwiftUI._UIHostingView.beginTransaction() -> () + 144 frame #10: 0x00000001d846aed0 SwiftUI`partial apply forwarder for closure #1 () -> () in closure #1 () -> () in closure #1 () -> () in SwiftUI._UIHostingView.beginTransaction() -> () + 20 frame #11: 0x00000001d984f814 SwiftUICore`closure #1 () throws -> τ_0_0 in static SwiftUI.Update.ensure<τ_0_0>(() throws -> τ_0_0) throws -> τ_0_0 + 48 frame #12: 0x00000001d984e114 SwiftUICore`static SwiftUI.Update.ensure<τ_0_0>(() throws -> τ_0_0) throws -> τ_0_0 + 96 frame #13: 0x00000001d846aeac SwiftUI`partial apply forwarder for closure #1 () -> () in closure #1 () -> () in SwiftUI._UIHostingView.beginTransaction() -> () + 64 frame #14: 0x00000001851eab1c UIKitCore`___lldb_unnamed_symbol311742 + 20 * frame #15: 0x00000001852b56a8 UIKitCore`___lldb_unnamed_symbol315200 + 44 frame #16: 0x0000000185175120 UIKitCore`___lldb_unnamed_symbol308851 + 20 frame #17: 0x00000001d984e920 SwiftUICore`static SwiftUI.Update.dispatchImmediately<τ_0_0>(reason: Swift.Optional<SwiftUI.CustomEventTrace.ActionEventType.Reason>, _: () -> τ_0_0) -> τ_0_0 + 300 frame #18: 0x00000001d95a7428 SwiftUICore`static SwiftUI.ViewGraphHostUpdate.dispatchImmediately<τ_0_0>(() -> τ_0_0) -> τ_0_0 + 40 frame #19: 0x00000001852b59dc UIKitCore`___lldb_unnamed_symbol315204 + 192 frame #20: 0x00000001852b54a4 UIKitCore`___lldb_unnamed_symbol315199 + 64 frame #21: 0x0000000185745dd4 UIKitCore`_UIUpdateSequenceRunNext + 120 frame #22: 0x0000000186144fac UIKitCore`schedulerStepScheduledMainSectionContinue + 56 frame #23: 0x00000002505ad150 UpdateCycle`UC::DriverCore::continueProcessing() + 36 frame #24: 0x0000000180445b20 CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 24 frame #25: 0x0000000180445a68 CoreFoundation`__CFRunLoopDoSource0 + 168 frame #26: 0x00000001804451f4 CoreFoundation`__CFRunLoopDoSources0 + 220 frame #27: 0x00000001804443a8 CoreFoundation`__CFRunLoopRun + 756 frame #28: 0x000000018043f458 CoreFoundation`_CFRunLoopRunSpecificWithOptions + 496 frame #29: 0x00000001928d19bc GraphicsServices`GSEventRunModal + 116 frame #30: 0x0000000186224480 UIKitCore`-[UIApplication _run] + 772 frame #31: 0x0000000186228650 UIKitCore`UIApplicationMain + 124 frame #32: 0x000000010bb1b504 MyApp.debug.dylib`main at main.swift:13:1 frame #33: 0x00000001043813d0 dyld_sim`start_sim + 20 frame #34: 0x000000010468ab98 dyld`start + 6076 Used let _ = Self.printChanges() in my SwiftUI View and got infinite changes of \_UICornerProvider.<computed 0x000000018527ffd8 (Optional<UICoordinateSpace>)> changed. Reproduces only on beta; works on stable iOS. Likely beta-specific bug in SwiftUI rendering.
6
1
310
4w
`.task(id:_:)` starting in the `Task.isCancelled` state
I'm running into a weird SwiftUI concurrency issue that only seems to happen on a real device (iOS 18.5 in my case), and not in simulator. I have a NavigationSplitView where the Detail view uses .task(id:_:) to perform some async work upon appearance (in my real-world case, a map snapshot). When running this on a real device, the first execution of the task works as expected. However, any task subsequent executions, even ones for the same id, always start in the Task.isCancelled state. Is there something about .task(id:_:) that I'm misunderstanding, or have I stumbled upon a serious bug here? import SwiftUI struct ContentView: View { var body: some View { TaskBugSplitView() } } struct TestItem: Identifiable, Hashable { var id: Int var name: String } struct TaskBugSplitView: View { @State private var selectedItemIndex: [TestItem].Index? @State private var testItems: [TestItem] = [ TestItem(id: 1, name: "First Item"), TestItem(id: 2, name: "Second Item"), TestItem(id: 3, name: "Third Item"), TestItem(id: 4, name: "Fourth Item"), TestItem(id: 5, name: "Fifth Item") ] var body: some View { NavigationSplitView { List(testItems.indices, id: \.self, selection: $selectedItemIndex) { item in Text(testItems[item].name) } } detail: { if let selectedItemIndex { TaskBugDetailView(item: testItems[selectedItemIndex]) } else { Text("Select an item") .foregroundStyle(.secondary) } } } } struct TaskBugDetailView: View { @State var item: TestItem @State private var taskResult = "Not started" var body: some View { VStack(spacing: 20) { Text("Item: \(item.name)") .font(.title2) Text("Task Result:") .font(.headline) Text(taskResult) .foregroundStyle(taskResult.contains("CANCELLED") ? .red : .primary) Spacer() } .padding() .navigationTitle(item.name) .task(id: item.id) { // BUG: On real devices, Task.isCancelled is true immediately for all tasks // after the first successful one, even though the ID has changed if Task.isCancelled { taskResult = "CANCELLED at start" print("Task cancelled at start for item \(item.id)") return } taskResult = "SUCCESS" print("Task completed successfully for item \(item.id)") } } }
2
0
63
4w
Background Modes, ScreenTime API
I’m attempting to run Apple’s ScreenTime API while my app is in the background When debugging on a device my background restrictions functionality works, but on TestFlight it does not. This is the error message when analyzing the device in XCodes Console BackgroundTaskSuspended. Background entitlement: NO When the proper entitlements are added this error doesn't allow for the build to be uploaded to TestFlight. Provisioning profile "iOS Team Provisioning Profile: com.xxx.xxx" doesn't include the UIBackgroundModes entitlement. I have the proper entries in the “Signing and Capabilities” of the project, but my functionality will not run in the background when the app is not launched. I just need a function to run that calls Apple's ScreenTime API while my app is in the background. Other apps have achieved the functionality I’m looking for so I know it’s possible, but this is the roadblock I’m running into.
2
0
127
4w
Implicit list row animations broken in Form container on iOS 26 beta 3
[Submitted as FB18870294, but posting here for visibility.] In iOS 26 beta 3 (23A5287g), implicit animations no longer work when conditionally showing or hiding rows in a Form. Rows with Text or other views inside a Section appear and disappear abruptly, even when wrapped in withAnimation or using .animation() modifiers. This is a regression from iOS 18.5, where the row item animates in and out correctly with the same code. Repro Steps Create a new iOS App › SwiftUI project. Replace its ContentView struct with the code below Build and run on an iOS 18 device. Tap the Show Middle Row toggle and note how the Middle Row animates. Build and run on an iOS 26 beta 3 device. Tap the Show Middle Row toggle. Expected Middle Row item should smoothly animate in and out as it does on iOS 18. Actual Middle Row item appears and disappears abruptly, without any animation. Code struct ContentView: View { @State private var showingMiddleRow = false var body: some View { Form { Section { Toggle( "Show **Middle Row**", isOn: $showingMiddleRow.animation() ) if showingMiddleRow { Text("Middle Row") } Text("Last Row") } } } }
3
3
174
Aug ’25
SwiftUI iOS 16 TabView PageTabViewStyle index behavior is wrong for right to left layoutDirection
TabView page control element has a bug on iOS 16 if tabview is configured as RTL with PageTabViewStyle. Found iOS 16 Issues: Page indicators display dots in reverse order (appears to treat layout as LTR while showing RTL) Index selection is reversed - tapping indicators selects wrong pages Using the page control directly to navigate eventually breaks the index binding The underlying index counting logic conflicts with the visual presentation iOS 18 Behavior: Works as expected with correct dot order and index selection. Xcode version: Version 16.3 (16E140) Conclusion: Confirmed broken on iOS 16 Confirmed working on iOS 18 iOS 17 and earlier versions not yet tested I've opened a feedback assistant ticket quite a while ago but there is no answer. There's a code example and a video there. Anyone else had experience with this particular bug? Here's the code: public struct PagingView<Content: View>: View { //MARK: - Public Properties let pages: (Int) -> Content let numberOfPages: Int let pageMargin: CGFloat @Binding var currentPage: Int //MARK: - Object's Lifecycle public init(currentPage: Binding<Int>, pageMargin: CGFloat = 20, numberOfPages: Int, @ViewBuilder pages: @escaping (Int) -> Content) { self.pages = pages self.numberOfPages = numberOfPages self.pageMargin = pageMargin _currentPage = currentPage } //MARK: - View's Layout public var body: some View { TabView(selection: $currentPage) { ForEach(0..<numberOfPages, id: \.self) { index in pages(index) .padding(.horizontal, pageMargin) } } .tabViewStyle(PageTabViewStyle(indexDisplayMode: .always)) .ignoresSafeArea() } } //MARK: - Previews struct ContentView: View { @State var currentIndex: Int = 0 var body: some View { ZStack { Rectangle() .frame(height: 300) .foregroundStyle(Color.gray.opacity(0.2)) PagingView( currentPage: $currentIndex.onChange({ index in print("currentIndex: ", index) }), pageMargin: 20, numberOfPages: 10) { index in ZStack { Rectangle() .frame(width: 200, height: 200) .foregroundStyle(Color.gray.opacity(0.2)) Text("\(index)") .foregroundStyle(.brown) .background(Color.yellow) } }.frame(height: 200) } } } #Preview("ContentView") { ContentView() } extension Binding { @MainActor func onChange(_ handler: @escaping (Value) -> Void) -> Binding<Value> { Binding( get: { self.wrappedValue }, set: { newValue in self.wrappedValue = newValue handler(newValue) } ) } }
0
0
78
Aug ’25
Clarification on safeAreaBar
I've been testing the safeAreaBar modifier to develop a custom tab bar. From my understanding, this should enable the .scrollEdgeEffectStyle to work with this bar, but I don't see any effect. Could you please clarify the difference between safeAreaBar and safeAreaInset?
Topic: UI Frameworks SubTopic: SwiftUI Tags:
4
3
158
Aug ’25
SwiftUI preview for drag/drop APIs
The new drag & drop APIs for macOS 26 are terrific, but there's an important missing piece. If I use draggable(containerItemID:), there's no way to provide a custom view for the drag image. Meanwhile the older API lets you provide a preview, but you miss out on things like multi-item drag and custom drag sessions. Is there some mechanism for supplying a preview that I'm not seeing? Without it, the drag interface in my apps is going to look terrible.
0
0
72
Aug ’25
iPadOS 26 Menu Bar - Copy / Paste
How to Support Menu Bar Copy/Paste/Cut/Delete Commands on iPadOS with SwiftUI? (Xcode 26 beta 4, iPadOS 26 beta 4) We’re working on adding menu bar support to our SwiftUI app on iPadOS, aiming to provide a more consistent and productive experience across platforms. However, we’ve encountered a challenge when trying to handle standard editing commands like Copy, Cut, Paste, and Delete from the menu bar: On iPadOS, SwiftUI modifiers such as onCopyCommand, onCutCommand, onPasteCommand, and onDeleteCommand appear to be unavailable. Additionally, since we can’t hide or override the default app menus, we’re unsure how to hook into or replace their behavior effectively. Question: What’s the recommended way to support standard editing actions like copy/paste via the menu bar in SwiftUI on iPadOS? Are there any workarounds or APIs we might have overlooked? Any guidance or best practices would be greatly appreciated! Feedback ID: FB18792279
1
0
66
Aug ’25
ScrollView ScrollPosition scrollTo Anchor ignored/broken
ScrollPosition does not obey anchor when calling scrollTo. The anchor is ignored and it does not matter what value you provide. If the view is below the visible content, it will pin the new scrolled to view at the bottom. If the view is already in the visible content, it will not scroll to the anchor. If the view is above the visible content, it will pin to top. All three cases ignore the anchor. This just another example of how painful SwiftUI is to work with. It just doesn't work as expected or intended, despite years of prioritizing ScrollView APIs. Link to Gist // This should scroll to item 50 with the requested anchor, but SCROLLPOSITION IGNORES THE ANCHOR. if shouldBeTopAnchor { // Expected: Scroll item 50 to top, but actually scrolls to bottom scrollPosition.scrollTo(id: 50, anchor: .top) } else { // Expected: Scroll item 50 to center, but actually scrolls to top scrollPosition.scrollTo(id: 50, anchor: .center) }
Topic: UI Frameworks SubTopic: SwiftUI
0
0
81
Aug ’25
watchOS 26 system clock collision
Our app has an infrequently used but useful calculator screen similar to Apple's calculator app where the current value ticker squats in the top toolbar trailing area, extending into the system clock area. In 26 beta, that view is now broken: the system clock not longer hides when a layout collision is detected. Can the prior avoidance behavior (or an API to hide the clock) be triggered somehow?
2
0
50
Aug ’25