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

Posts under SwiftUI tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Can we access a "Locked in Place" value when a window has been locked without being snapped to a surface?
Starting in visionOS 26, users can snap windows to surfaces. These windows are locked in place and are later restored by visionOS. We can access the snapped data with surfaceSnappingInfo docs. Users can also lock a free-floating (unsnapped) window from a context menu in the window controls. Is there a way to tell when a window has been locked without being snapped to a surface?
7
3
143
Jun ’25
How can I avoid overlapping the new iPadOS 26 window controls without using .toolbar?
I'm building an iPad app targeting iPadOS 26 using SwiftUI. Previously, I added a custom button by overlaying it in the top-left corner: content .overlay(alignment: .topLeading) { Button("Action") { // ... } This worked until iPadOS 26 introduced new window controls (minimize/close) in that corner, which now overlap my button. In the WWDC Session Video https://developer.apple.com/videos/play/wwdc2025/208/?time=298, they show adapting via .toolbar, but using .toolbar forces me to embed my view in a NavigationStack, which I don’t want. I really only want to add this single button, without converting the whole view structure. Constraints: No use of .toolbar (as it compels a NavigationStack). Keep existing layout—just one overlayed button. Support automatic adjustment for the new window controls across all window positions and split-screen configurations. What I’m looking for: A way to detect or read the system′s new window control safe area or layout region dynamically on iPadOS 26. Use that to offset my custom button—without adopting .toolbar. Preferably SwiftUI-only, no heavy view hierarchy changes. Is there a recommended API or SwiftUI technique to obtain the new control’s safe area (similar to a custom safeAreaInset for window controls) so I can reposition my overlayed button accordingly—without converting to NavigationStack or using .toolbar?
2
4
273
Jul ’25
How to inject parameter dependency at runtime in iOS App Intent
I am trying to create an App Intent that lets a user select a day in the itinerary of a trip. The trip has to be chosen before the days available can be displayed. When the PlanActivityIntentDemo intent is ran from the shortcuts app, the trip selected is not injected into the appropriate TripItineraryDayQueryDemo Entity Query. Is there a way to get the selected trip to be injected at run time from shortcuts app. Here's some code for illustration: // Entity Definition: import AppIntents struct ShortcutsItineraryDayEntityDemo: Identifiable, Hashable, AppEntity { typealias DefaultQuery = TripItineraryDayQueryDemo static var typeDisplayRepresentation: TypeDisplayRepresentation = "Trip Itinerary Day" var displayRepresentation: DisplayRepresentation { "Trip Day" } var id: String static var defaultQuery: DefaultQuery { TripItineraryDayQueryDemo() } init() { self.id = UUID().uuidString } } struct TripItineraryDayQueryDemo: EntityQuery { // This only works in shortcut editor but not at runtime. Why? How can I fix this issue? @IntentParameterDependency<PlanActivityIntentDemo>(\.$tripEntity) var tripEntity @IntentParameterDependency<PlanActivityIntentDemo>(\.$title) var intentTitle func entities(for identifiers: [ShortcutsItineraryDayEntityDemo.ID]) async throws -> [ShortcutsItineraryDayEntityDemo] { print("entities being called with identifiers: \(identifiers)") // This method is called when the app needs to fetch entities based on identifiers. let tripsStore = TripsStore() guard let trip = tripEntity?.tripEntity.trip, let itineraryId = trip.firstItineraryId else { print("No trip or itinerary ID can be found for the selected trip.") return [] } return [] // return empty for this demo } func suggestedEntities() async throws -> [ShortcutsItineraryDayEntityDemo] { print("suggested itinerary days being called") let tripsStore = TripsStore() guard let trip = tripEntity?.tripEntity.trip, let itineraryId = trip.firstItineraryId else { print("No trip or itinerary ID found for the selected trip.") return [] } return [] } } struct PlanActivityIntentDemo: AppIntent { static var title: LocalizedStringResource { "Plan New Activity" } // The selected trip fails to get injected when intent is run from shortcut app @Parameter(title: "Trip", description: "The trip to plan an activity for", requestValueDialog: "Which trip would you like to plan an activity for?") var tripEntity: ShortcutsTripEntity @Parameter(title: "Activity Title", description: "The title of the activity", requestValueDialog: "What do you want to do or see?") var title: String @Parameter(title: "Activity Day", description: "Activity Day") var activityDay: ShortcutsItineraryDayEntity func perform() async throws -> some ProvidesDialog { // This is a demo intent, so we won't actually perform any actions. .result(dialog: "Activity '\(title)' planned") } }
0
1
108
Jun ’25
New WebView (Xcode 26 beta) doesn't resize when NavigationSplitView sidebar appears
I'm using the new Swifty WebView in 26.0 beta (17A5241e). Previously, I would wrap WKWebView in a ViewRepresentable and place it in the detail area of a NavigationSplitView. The page content correctly shrunk when the sidebar was opened. Now, the page content takes up the full width of the NavigationSplitView and the sidebar hovers over the page content with a translucent effect. This is in spite of setting .navigationSplitViewStyle(.balanced). Code below. I believe this is a problem with the new WebView not respecting size hints from parent views in the hierarchy. This is because if I replace the WebView with a centered Text view, it shifts over correctly when the sidebar is opened. struct OccludingNavSplitView: View { var body: some View { NavigationSplitView { Text("Sidebar") } detail: { WebView(url: URL(string: "https://www.google.com")!) } .navigationSplitViewStyle(.balanced) } } #Preview("Occluding sidebar") { OccludingNavSplitView() }
2
0
78
Jun ’25
TabView on IPAD (IOS18.1)
Dear friends, I am trying to use IOS18 API for TabView. Below code works well on simulator Iphone 16 Pro Max. But, it failed to show UI on simulator Ipad Pro 13 . TabView(selection: $selectedTab) { Tab("Test1", systemImage: "bubble.left.and.bubble.right", value: .translation) { TestViewOne() } Tab("Test2", systemImage: "character.textbox", value: .ruby) { TestViewTwo() } Tab("Test3", systemImage: "person.crop.circle", value: .browser) { TestViewThree() } } There are 3 tabs, none of them can show the view (TestViewOne TestViewTwo TestViewThree ) until pressing button 4 (red 4 in the attached image). The view could show in the sidebar area instead of normal UI area, Is there any suggestions for this? thank you very much!
1
0
62
Jun ’25
`UIHostingConfiguration` for cells not cancelling touches on `UIScrollView` scroll (drag)?
The default behavior on UIScrollView is that "canCancelContentTouches" is true. If you add a UIButton to a UICollectionViewCell and then scroll (drag) the scroll view with a touch beginning on that button in that cell, it cancels ".touchUpInside" on the UIButton. However, if you have a Button in a SwiftUI view configured with "contentConfiguration" it does not cancel the touch, and the button's action is triggered if the user is still touching that cell when the scroll (drag) completes. Is there a way to forward the touch cancellations to the SwiftUI view, or is it expected that all interactivity is handled only in UIKit, and not inside of "contentConfiguration" in specific cases? This behavior seems to occur on all SwiftUI versions supporting UIHostingConfiguration so far.
4
0
60
Jun ’25
SwiftUI buttons behind NSToolbarView are not clickable on macOS 26 beta
Overview Starting with macOS 26 beta 1, a new NSGlassContainerView is added inside NSToolbarView. This view intercepts mouse events, so any SwiftUI Button (or other interactive view) overlaid on the title‑bar / toolbar area no longer receives clicks. (The same code works fine on macOS 15 and earlier.) Filed as FB18201935 via Feedback Assistant. Reproduction (minimal project) macOS 15 or earlier → button is clickable macOS 26 beta → button cannot be clicked (no highlight, no action call) @main struct Test_macOS26App: App { init() { // Uncomment to work around the issue (see next section) // enableToolbarClickThrough() } var body: some Scene { WindowGroup { ContentView() } .windowStyle(.hiddenTitleBar) // ⭐️ hide the title bar } } struct ContentView: View { var body: some View { NavigationSplitView { List { Text("sidebar") } } detail: { HSplitView { listWithOverlay listWithOverlay } } } private var listWithOverlay: some View { List(0..<30) { Text("item: \($0)") } .overlay(alignment: .topTrailing) { // ⭐️ overlay in the toolbar area Button("test") { print("test") } .glassEffect() .ignoresSafeArea() } } } Investigation In Xcode View Hierarchy Debugger, a layer chain NSToolbarView > NSGlassContainerView sits in front of the button. -[NSView hitTest:] on NSGlassContainerView returns itself, so the event never reaches the SwiftUI layer. Swizzling hitTest: to return nil when the result is the view itself makes the click go through: func enableToolbarClickThrough() { guard let cls = NSClassFromString("NSGlassContainerView"), let m = class_getInstanceMethod(cls, #selector(NSView.hitTest(_:))) else { return } typealias Fn = @convention(c)(AnyObject, Selector, NSPoint) -> Unmanaged<NSView>? let origIMP = unsafeBitCast(method_getImplementation(m), to: Fn.self) let block: @convention(block)(AnyObject, NSPoint) -> NSView? = { obj, pt in guard let v = origIMP(obj, #selector(NSView.hitTest(_:)), pt)?.takeUnretainedValue() else { return nil } return v === (obj as AnyObject) ? nil : v // ★ make the container transparent } method_setImplementation(m, imp_implementationWithBlock(block)) } Questions / Call for Feedback Is this an intentional behavioral change? If so, what is the recommended public API or pattern for allowing clicks to reach views overlaid behind the toolbar? Any additional data points or confirmations are welcome—please reply if you can reproduce the issue or know of an official workaround. Thanks in advance!
2
0
173
Jun ’25
SwiftUI app crashes (EXC_BAD_ACCESS) when view hierarchy becomes too large.
Hey! Our team is experiencing some issue in a large SwiftUI application. When loading large views, the app crashes with a EXC_BAD_ACCESS signal. This signal can be reported by Xcode either on the @main attribute, inside a view hierarchy, or any order property that is accessed in the view hierarchy. After some investigation we found several possible workarounds: Splitting up the view into smaller subviews Wrapping parts of the view into an AnyView, which isn't ideal. However, this only temporarily solved the issue. As the app becomes bigger, we run into this problem more frequently. When trying to reproduce this issue in a clean Xcode project, I came up with the following: struct ContentView: View { var body: some View { Text("Hello") .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} .task {} } } When running this, the app immediately crashes on an iPhone 14 (YMMV on different (newer) devices). Of course such a view is not very likely to occur, but in total a view hierarchy could have this many view modifiers. Is there some limit we should we aware of? How can we circumvent this? Thanks!
0
0
43
Jun ’25
SwiftUI window top left aligned on macOS 26 beta 1
We ran into a bug with our app Bezel (https://getbezel.app). When running on macOS Tahoe, windows would get partially clipped. This is because we have SwiftUI views that are larger than the window size, our SwiftUI views are supposed to be centered, which they are on macOS 13, 14, 15. But on macOS 26 (beta 1), the window contents are top-left aligned. This seems to be a bug, I have submitted FB18201269. This is my code: WindowGroup { ZStack { Color.green ZStack { Color.yellow Text("Hi") } .aspectRatio(1, contentMode: .fill) .border(.red) } } This first screenshot shows the old behavior on macOS 15: This second screenshot shows the new behavior on macOS 26 (beta 1) Can anyone confirm if this is indeed a bug, or if this an intended change in behavior?
1
0
55
Jun ’25
Detect when tab bar minimizes (.tabBarMinimizeBehavior)
Hi! I'm working on a iOS 26 SwiftUI prototype that adds an element to the content of a screen only when the tab bar is fully visible and not minimized (via .tabBarMinimizeBehavior). Is there any way to detect when a tab bar is minimized? My hope is that I can use a ternary operator to display something only when a boolean is true. Here's some code to illustrate my idea: struct ContentView: View { @State var isTabBarMinimized: Bool = false var body: some View { TabView { Tab("View1", systemImage: "rainbow") { // Only appears when tab bar is fully visible Color.blue .opacity(isTabBarMinimized? 0 : 1 ) } Tab("View2", systemImage: "rainbow") { View2() } Tab("View3", systemImage: "rainbow") { View3() } Tab("View4", systemImage: "rainbow") { View4() } } .tabBarMinimizeBehavior(.onScrollDown) } }
1
0
117
Jun ’25
Error querying optional Codable with SwiftData
I'm building a SwiftUI app using SwiftData. In my app I have a Customer model with an optional codable structure Contact. Below is a simplified version of my model: @Model class Customer { var name: String = "" var contact: Contact? init(name: String, contact: Contact? = nil) { self.name = name self.contact = contact } struct Contact: Codable, Equatable { var phone: String var email: String var allowSMS: Bool } } I'm trying to query all the Customers that have a contact with @Query. For example: @Query(filter: #Predicate<Customer> { customer in customer.contact != nil }) var customers: [Customer] However no matter how I set the predicate I always get an error: BugDemo crashed due to an uncaught exception NSInvalidArgumentException. Reason: keypath contact not found in entity Customer. How can I fix this so that I'm able to filter by contact not nil in my Model?
2
0
188
Jun ’25
How to do full width .sheet() on iOS 26+ with small presentation detents?
For certain contexts, I'd like to still have my .sheet() be full width even when it's at a small height. In iOS 26, the sheet is inset from the edges at small detents and expands to full width at larger detents. For example, I have a view where I have a .sheet() that has a height of about 200pts and it contains a horizontally scrolling picker that extends past the bounds of the screen. I'd like the .sheet to expand all the way to the edge when at these small detents, like it would previous to iOS 26. Is it possible to configure this? This change will break a number of existing designs :( A new ViewModifier such as enum PresentationWidth { case dynamic, fixed } func presentationWidth(_ width: PresentationWidth) -> some View would be very nice.
1
2
79
Jun ’25
Detect when app window is being moved
Is there a way to detect when your apps (or any app I guess) is being moved by the user clicking and dragging the main window around the desktop at all? I'm trying to find out if there's a way I can find out if a window is being clicked and dragged and whether there's certain triggers to the movement a little bit like shaking an iPhone with Shake to Undo. Thanks
0
0
41
Jun ’25
ViewThatFits and Text Truncation
I'm using ViewThatFits to handle different screen sizes as well as the orientation of the phone. Essentially, I have a smaller view that should only be used in portrait mode on the phone and a larger view that should be used in every other instance. The issue is that both of those views have a Text view that is bound to a String within a SwiftData model. If the String is too long the ViewThatFits considers that when choosing the appropriate subview. This results in a list of items where most items use one view while one or more may use the other view. It would be great if there was a modifier that could be applied to the Text view that resulted in the ViewThatFits ignoring it when determining the appropriate subview. Until such a modifier is available, has anyone come up with creative ways around this?
1
0
49
Jun ’25
NavigationStack wrong behaviour in iOS 18.3
Hi, Anybody knows will this occurs when using navigationStack at iOS 18.3? The navigationStack not stay at safeareas the code as simple as that: NavigationStack(path: $navManager.path) { VStack { Text("Hello") } .navigationDestination(for: Route.self) { route in switch route { .... } } } .environmentObject(navManager) .environment(logic)
0
0
87
Jun ’25
Alternatives to SceneView
Hey there, since SceneView has been marked as „deprecated“ for SwiftUI, I‘m wondering which alternatives should be considered for the following situation: I have a SwiftUI app (for iOS and iPadOS) where users can view (with rotate, scale, move gestures) 3D models (USDZ) in a scene. The models will be downloaded from web backend and called via local URL paths. What I tested: I‘ve tried ARView in .nonAR mode, RealityView, however I didn‘t get the expected response -> User can rotate, scale the 3D models in a virtual space. ARView in nonAR mode still shows the object like in normal AR mode without camera stream. I tried to add Gestures to the RealityView on iOS - loading USDZ 3D models worked but the gestures didn’t). Model3D is only available for visionOS (that would be amazing to have it for iOS) I also checked QuickLook Preview however it works pretty strange via Filepicker etc, which is not the way how the user should load the 3D models in my app. Maybe I missed something, I couldn’t find anything which can help me. I‘m pretty much stucked adopting the latest and greatest frameworks/APIs in my App and taking the next steps porting my app to visionOS. Long story short 😃: Does someone have an idea what is the alternative to SceneView for USDZ 3D models? I appreciate your support!! Thanks in advance!
4
0
136
Jul ’25
encounter memory leak for SVG image
I have a memory leak for SVG image that located in Assets.xcassets file when using SwiftUI Image, but when I use UIImage then convert it to SwiftUI Image the issue is not found. import SwiftUI struct ContentView: View { var body: some View { NavigationStack { VStack { NavigationLink("Show", destination: SecondView()) } .padding() } } } struct SecondView: View { @Environment(\.dismiss) var dismiss var body: some View { NavigationStack { VStack { IM.svgImage .resizable() .scaledToFit() .frame(width: 200, height: 200) Button("Dismiss") { dismiss() } } } } } enum IM { static let testImage: Image = "test_image".image static let svgImage: Image = "svgImage".image } extension String { var image: Image { Image(self) // Memory leak } var imageFromUIImage: Image { guard let uiImage = UIImage(named: self) else { return Image(self) } return Image(uiImage: uiImage) // No Memory leak } } Environment that produces the issue: Xcode: 16.2 Simulator: iPhone 15 Pro (iOS 17.5)
1
0
71
Jun ’25
Can't display image in SwiftUI
I'm trying to display my apps icon within my app and it's not working. It displays a blank space instead and I don't understand why this is happening. I tried creating a new image (just a normal image, not an 'App Icon' image set) and have this code: Image("AppIcon") .resizable() .aspectRatio(contentMode: .fit) .frame(width: 48) .cornerRadius(10) .overlay( RoundedRectangle(cornerRadius: 10) .stroke(Color.black.opacity(0.1), lineWidth: 1) ) For some strange reason it's not displaying that either. The image name is correct. It's showing a blank white box.
2
0
87
Jun ’25