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

A Summary of the WWDC25 Group Lab - SwiftUI
At WWDC25 we launched a new type of Lab event for the developer community - Group Labs. A Group Lab is a panel Q&A designed for a large audience of developers. Group Labs are a unique opportunity for the community to submit questions directly to a panel of Apple engineers and designers. Here are the highlights from the WWDC25 Group Lab for SwiftUI. What's your favorite new feature introduced to SwiftUI this year? The new rich text editor, a collaborative effort across multiple Apple teams. The safe area bar, simplifying the management of scroll view insets, safe areas, and overlays. NavigationLink indicator visibility control, a highly requested feature now available and back-deployed. Performance improvements to existing components (lists, scroll views, etc.) that come "for free" without requiring API adoption. Regarding performance profiling, it's recommended to use the new SwiftUI Instruments tool when you have a good understanding of your code and notice a performance drop after a specific change. This helps build a mental map between your code and the profiler's output. The "cause-and-effect graph" in the tool is particularly useful for identifying what's triggering expensive view updates, even if the issue isn't immediately apparent in your own code. My app is primarily UIKit-based, but I'm interested in adopting some newer SwiftUI-only scene types like MenuBarExtra or using SwiftUI-exclusive features. Is there a better way to bridge these worlds now? Yes, "scene bridging" makes it possible to use SwiftUI scenes from UIKit or AppKit lifecycle apps. This allows you to display purely SwiftUI scenes from your existing UIKit/AppKit code. Furthermore, you can use SwiftUI scene-specific modifiers to affect those scenes. Scene bridging is a great way to introduce SwiftUI into your apps. This also allows UIKit apps brought to Vision OS to integrate volumes and immersive spaces. It's also a great way to customize your experience with Assistive Access API. Can you please share any bad practices we should avoid when integrating Liquid Glass in our SwiftUI Apps? Avoid these common mistakes when integrating liquid glass: Overlapping Glass: Don't overlap liquid glass elements, as this can create visual artifacts. Scrolling Content Collisions: Be cautious when using liquid glass within scrolling content to prevent collisions with toolbar and navigation bar glass. Unnecessary Tinting: Resist the urge to tint the glass for branding or other purposes. Liquid glass should primarily be used to draw attention and convey meaning. Improper Grouping: Use the GlassEffectContainer to group related glass elements. This helps the system optimize rendering by limiting the search area for glass interactions. Navigation Bar Tinting: Avoid tinting navigation bars for branding, as this conflicts with the liquid glass effect. Instead, move branding colors into the content of the scroll view. This allows the color to be visible behind the glass at the top of the view, but it moves out of the way as the user scrolls, allowing the controls to revert to their standard monochrome style for better readability. Thanks for improving the performance of SwiftUI List this year. How about LazyVStack in ScrollView? Does it now also reuse the views inside the stack? Are there any best practices for improving the performance when using LazyVStack with large number of items? SwiftUI has improved scroll performance, including idle prefetching. When using LazyVStack with a large number of items, ensure your ForEach returns a static number of views. If you're returning multiple views within the ForEach, wrap them in a VStack to signal to SwiftUI that it's a single row, allowing for optimizations. Reuse is handled as an implementation detail within SwiftUI. Use the performance instrument to identify expensive views and determine how to optimize your app. If you encounter performance issues or hitches in scrolling, use the new SwiftUI Instruments tool to diagnose the problem. Implementing the new iOS 26 tab bar seems to have very low contrast when darker content is underneath, is there anything we should be doing to increase the contrast for tab bars? The new design is still in beta. If you're experiencing low contrast issues, especially with darker content underneath, please file feedback. It's generally not recommended to modify standard system components. As all apps on the platform are adopting liquid glass, feedback is crucial for tuning the experience based on a wider range of apps. Early feedback, especially regarding contrast and accessibility, is valuable for improving the system for all users. If I’m starting a new multi-platform app (iOS/iPadOS/macOS) that will heavily depend on UIKit/AppKit for the core structure and components (split, collection, table, and outline views), should I still use SwiftUI to manage the app lifecycle? Why? Even if your new multi-platform app heavily relies on UIKit/AppKit for core structure and components, it's generally recommended to still use SwiftUI to manage the app lifecycle. This sets you up for easier integration of SwiftUI components in the future and allows you to quickly adopt new SwiftUI features. Interoperability between SwiftUI and UIKit/AppKit is a core principle, with APIs to facilitate going back and forth between the two frameworks. Scene bridging allows you to bring existing SwiftUI scenes into apps that use a UIKit lifecycle, or vice versa. Think of it not as a binary choice, but as a mix of whatever you need. I’d love to know more about the matchedTransitionSource API you’ve added - is it a native way to have elements morph from a VStack to a sheet for example? What is the use case for it? The matchedTransitionSource API helps connect different views during transitions, such as when presenting popovers or other presentations from toolbar items. It's a way to link the user interaction to the presented content. For example, it can be used to visually connect an element in a VStack to a sheet. It can also be used to create a zoom effect where an element appears to enlarge, and these transitions are fully interactive, allowing users to swipe. It creates a nice, polished experience for the user. Support for this API has been added to toolbar items this year, and it was already available for standard views.
Topic: UI Frameworks SubTopic: SwiftUI
1
0
1.1k
Jun ’25
WidgetKit + AppIntent widget never sees shared snapshots (Flutter host app)
Environment iOS 17.2, Xcode 16.2, physical iPhone (12 Pro) Main app in Flutter WidgetKit extension written in Swift (Swift‑PM package) Shared App Group: group.cool.glance.shared Widget uses an AppIntent (FeedSelectionIntent) + custom entity (FeedAppEntity) Flutter bridge writes JSON snapshots for the widget Observed behaviour Flutter prints the snapshot payload and writes /…/AppGroup/<uuid>/Library/Caches/feed_snapshots.json. Widget gallery only shows the plain grey system placeholder (my sample placeholder never appears). Console log every time WidgetKit runs: chronod: Unable to resolve default intent (appintent:FeedSelectionIntent) for extension cool.glance.app.widget Error Domain=LNMetadataProviderErrorDomain Code=9000 LinkMetadata.BundleMetadataExtractionError.aggregateMetadataIsEmpty Added os_log in the widget + bridge (WidgetsBridgePlugin, FeedSnapshotStore, FeedEntityQuery, FeedSummaryTimeline), but none of them ever appear. That suggests the widget bundle can’t see the compiled AppIntent metadata or the snapshot file even though it’s there. Code (trimmed to essentials) FeedSelectionIntent.swift struct FeedSelectionIntent: AppIntent, WidgetConfigurationIntent { static var title: LocalizedStringResource = "Feed" static var description = IntentDescription("Choose which feed should appear in the widget.") @Parameter(title: "Feed", requestValueDialog: IntentDialog("Select which feed to display.")) var feed: FeedAppEntity? static var parameterSummary: some ParameterSummary { Summary("Show \(\.$feed)") } init() { feed = FeedAppEntity.sample } init(feed: FeedAppEntity?) { self.feed = feed } static var defaultValue: FeedSelectionIntent { FeedSelectionIntent(feed: .sample) } func perform() async throws -> some IntentResult { .result() } } FeedSnapshotStore.loadSnapshots() guard let containerURL = fileManager.containerURL( forSecurityApplicationGroupIdentifier: appGroupIdentifier) else { os_log("FeedSnapshotStore: missing app group container %{public}s", log: Self.log, type: .error, appGroupIdentifier) return [] } let fileURL = SharedConstants.feedSnapshotRelativePath.reduce(containerURL) { url, component in url.appendingPathComponent(component, isDirectory: component != SharedConstants.feedSnapshotFileName) } guard let data = try? Data(contentsOf: fileURL), !data.isEmpty else { os_log("FeedSnapshotStore: no snapshot data found at %{public}s", log: Self.log, type: .info, fileURL.path) return [] } // decode FeedSnapshotEnvelope… WidgetsBridgePlugin.writeSnapshots (Flutter → widget) guard let containerURL = fileManager.containerURL( forSecurityApplicationGroupIdentifier: SharedConstants.appGroupIdentifier) else { result(FlutterError(code: "container-unavailable", message: "Unable to locate shared app group container.", details: nil)) return } let targetDir = SharedConstants.feedSnapshotRelativePath.dropLast().reduce(containerURL) { $0.appendingPathComponent($1, isDirectory: true) } try fileManager.createDirectory(at: targetDir, withIntermediateDirectories: true) let targetURL = targetDir.appendingPathComponent(SharedConstants.feedSnapshotFileName, isDirectory: false) try data.write(to: targetURL, options: .atomic) WidgetCenter.shared.reloadTimelines(ofKind: "GlanceSummaryWidget") os_log("WidgetsBridgePlugin: wrote snapshots for %{public}d feeds at %{public}s", log: WidgetsBridgePlugin.log, type: .info, envelope.feeds.count, targetURL.path) Info.plist for the widget contains only: <key>NSExtensionPointIdentifier</key> <string>com.apple.widgetkit-extension</string> <key>NSExtensionAttributes</key> <dict> <key>WKAppBundleIdentifier</key> <string>cool.glance.app</string> </dict> (If I add NSExtensionPrincipalClass, the install fails with “principal class not allowed for com.apple.widgetkit-extension”, so it stays out.) What I’ve double‑checked App Group entitlement present on Runner.app and the widget extension. Snapshot file definitely exists under Library/Caches/feed_snapshots.json (size updates when Flutter writes). Code matches Apple’s “Making a configurable widget” sample (custom WidgetConfigurationIntent, entity, and timeline provider). Cleaned build folders (Flutter + Xcode), reinstalled app from scratch, but I still don’t see any of the os_log messages from the widget extension-only the LinkMetadata error above. Placeholder entry (SampleSnapshots.recentSummary) is wired up; yet the system never uses it and always drops to the generic grey preview. Questions Does LinkMetadata.BundleMetadataExtractionError.aggregateMetadataIsEmpty mean WidgetKit can’t see the compiled AppIntent metadata? If so, what could cause that when the extension is built via Swift Package Manager inside a Flutter project? Are there extra build settings or plist keys required so the AppIntent metadata gets embedded in the widget bundle? Any reason the widget would never reach my FeedSnapshotStore logs even though the file is written and the App Group is configured? Any help connecting the dots would be hugely appreciated.
0
0
101
17h
In SwiftUI on macOS, using instancing in RealityKit, how can I set individual colours per instance?
I have written this function: @available(macOS 26.0, *) func instancing() async -> Entity { let entity = Entity() do { // 1. Create a CustomMaterial let library = offscreenRenderer.pointRenderer!.device.makeDefaultLibrary()! let surfaceShader = CustomMaterial.SurfaceShader( named: "surfaceShaderWithCustomUniforms", // This must match the function name in Metal in: library ) let instanceCount = 10 // No idea how to actually use this... // let bufferSize = instanceCount * MemoryLayout<UInt32>.stride // // // Create the descriptor // var descriptor = LowLevelBuffer.Descriptor(capacity: bufferSize, sizeMultiple: MemoryLayout<UInt32>.stride) // // // Initialize the buffer // let lowLevelBuffer = try LowLevelBuffer(descriptor: descriptor) // lowLevelBuffer.withUnsafeMutableBytes { rawBytes in // // Bind the raw memory to the UInt32 type // let pointer = rawBytes.bindMemory(to: UInt32.self) // pointer[1] = 0xff_0000 // pointer[0] = 0x00_ff00 // pointer[2] = 0x00_00ff // pointer[3] = 0xff_ff00 // pointer[4] = 0xff_00ff // pointer[5] = 0x00_ffff // pointer[6] = 0xff_ffff // pointer[7] = 0x7f_0000 // pointer[8] = 0x00_7f00 // pointer[9] = 0x00_007f // } var material = try CustomMaterial(surfaceShader: surfaceShader, lightingModel: .lit) material.withMutableUniforms(ofType: SurfaceCustomUniforms.self, stage: .surfaceShader) { params, resources in params.argb = 0xff_0000 } // 2. Create the ModelComponent (provides the MESH and MATERIAL) let mesh = MeshResource.generateSphere(radius: 0.5) let modelComponent = ModelComponent(mesh: mesh, materials: [material]) // 3. Create the MeshInstancesComponent (provides the INSTANCE TRANSFORMS) let instanceData = try LowLevelInstanceData(instanceCount: instanceCount) instanceData.withMutableTransforms { transforms in for i in 0..<instanceCount { let instanceAngle = 2 * .pi * Float(i) / Float(instanceCount) let radialTranslation: SIMD3<Float> = [-sin(instanceAngle), cos(instanceAngle), 0] * 4 // Position each sphere around a circle. let transform = Transform( scale: .one, rotation: simd_quatf(angle: instanceAngle, axis: [0, 0, 1]), translation: radialTranslation ) transforms[i] = transform.matrix } } let instancesComponent = try MeshInstancesComponent(mesh: mesh, instances: instanceData) // 4. Attach BOTH to the same entity entity.components.set(modelComponent) entity.components.set(instancesComponent) } catch { print("Failed to create mesh instances: \(error)") } return entity } and this is the corresponding Metal shader typedef struct { uint32_t argb; } SurfaceCustomUniforms; [[stitchable]] void surfaceShaderWithCustomUniforms(realitykit::surface_parameters params, constant SurfaceCustomUniforms &customParams) { half3 color = { static_cast<half>((customParams.argb >> 16) & 0xff), static_cast<half>((customParams.argb >> 8) & 0xff), static_cast<half>(customParams.argb & 0xff) }; params.surface().set_base_color(color); } which works well and generates 10 red spheres. While listening to the WWDC25 presentation on what's new in RealityKit I am positive to hear the presenter saying that it is possible to customise each instance using a LowLevelBuffer, but so far all my attempts have failed. Is it possible, and if so how ? Thanks for reading and for your help. Kind regards, Christian
1
1
181
1d
.bottomBar menu button briefly disappears after menu dismissal on iOS 26.1 Seed 2 (23B5059e)
[Also submitted as FB20636175] In iOS 26.1 Seed 2 (23B5059e), ToolbarItem menus with .bottomBar placement cause the toolbar item to disappear and rebuild after the menu is dismissed, instead of smoothly morphing back. The bottom toolbar can take 1–2 seconds to reappear. This also seems to coincide with this console error: Adding 'UIKitToolbar' as a subview of UIHostingController.view is not supported and may result in a broken view hierarchy. Add your view above UIHostingController.view in a common superview or insert it into your SwiftUI content in a UIViewRepresentable instead. This occurs both on device and in a simulator. Sample Project This sample ContentView includes two menu buttons—one in the bottom bar and one in the top bar. Dismissing the bottom bar menu causes a short delay before the button reappears, while the top bar menu behaves normally. struct ContentView: View { var body: some View { NavigationStack { Text("Tap and dismiss both menu buttons and note the difference.") .navigationTitle("BottomBar Menu Issue") .navigationSubtitle("Reproduces on iOS 26.1 Seed 2 (23B5059e)") .toolbar { // Control: top bar trailing menu animates back smoothly ToolbarItem(placement: .topBarTrailing) { Menu { Button("Dismiss", role: .cancel) { } Button("Do Nothing") { } } label: { Label("More", systemImage: "ellipsis.circle") .font(.title3) } } // Repro: delay before menu button reappears after menu dismissal ToolbarItem(placement: .bottomBar) { Menu { Button("Dismiss", role: .cancel) { } Button("Do Nothing") { } } label: { Label("Actions", systemImage: "ellipsis.circle") .font(.title2) } } } } } } Passwords App This can also be seen in iOS 26.1 Seed 2 (23B5059e)'s Passwords app ("All" or "Passcodes" views):
1
2
258
1d
SwiftUI view state resetting after alert is shown
Seeing an issue in iOS 26.2 iPhone 17 simulator (haven't been able to reproduce on device or other simulators), where a view's state is reset after an alert is shown. In this example the first LibraryView has the issue when alert is shown, the second LibraryView maintains state as expected. struct ContentView: View { var body: some View { NavigationStack { List { VStack { LibraryView(title: "Show view (Loss of state)") } LibraryView(title: "Show view (Works as expected)") } } } } /// This view is from a package dependency and wants to control the presentation of the sheet internally public struct LibraryView: View { @State private var isPresented: Bool = false let title: String public init(title: String) { self.title = title } public var body: some View { Button(self.title) { self.isPresented = true } .sheet(isPresented: self.$isPresented) { ViewWithAlert() } } } private struct ViewWithAlert: View { @State private var isPresented: Bool = false @State private var presentedCount = 0 var body: some View { Button("Show Alert, count: \(presentedCount)") { isPresented = true presentedCount += 1 } .alert("Hello", isPresented: self.$isPresented) { Button("OK") { } } } } Any ideas? The issue can be corrected by moving the .sheet to a higher level within the layout (i.e. on the NavigationStack). However, the library wants to control that presentation and not require the integration to present the sheet.
Topic: UI Frameworks SubTopic: SwiftUI
10
1
347
1d
Horrible weird Window Server killing bug
OS 26.s, Xcode 26.2 TLDR: My pure SwiftUI app freezes the window server, is this a known problem? My app is pure SwiftUI, no low level calls, no networking, no tricksy pointer use. Somehow, something in my code is terminally confusing the Window Server. As in, I run the app, and before I ever seen a window, the Window Server locks up, and is killed by the OS for being unresponsive. Using debugging shows that I get to the end of a Canvas, and it simply freezes upon exiting. I'm about to do the old comment out everything, and bring it back a bit at a time, but I'm wondering if anyone is experiencing this sort of thing? The reaction is so extreme. And it's not Xcode in particular, I built the program with xcodebuild, Xcode itself not running, and ran my app, and it did the same thing.
Topic: UI Frameworks SubTopic: SwiftUI
2
0
63
1d
.contactAccessPicker shows blank sheet on iOS 26.2.1 on device
Calling contactAccessPicker results in a blank sheet and a jetsam error, rather than the expected contact picker, using Apple’s sample code, only on device with iOS 26.2.1. This is happening on a iPhone 17 Pro Max running 26.2.1, and not on a simulator. I’m running Apple's sample project Accessing a person’s contact data using Contacts and ContactsUI Steps: Run the sample app on device running iOS 26.2.1. Use the flow to authorize .limited access with 1 contact: Tap request access, Continue, Select Contacts. Select a contact, Continue, Allow Selected Contact. This all works as expected. Tap the add contact button in the toolbar to add a second contact. Expected: This should show the Contact Access Picker UI. Actual: Sheet is shown with no contents. See screenshot of actual results on iOS device running 26.2.1. Reported as FB21812568 I see a similar (same?) error reported for 26.1. It seems strange that the feature is completely broken for multiple point releases. Is anyone else seeing this or are the two of us running into the same rare edge case? Expected Outcome, seen on simulator running 26.2 Actual outcome, seen on device running 26.2.1
1
0
42
1d
Issues with ScrollView and nested (Lazy)VStack
Hello, We're having massive issues when we nest LazyVStacks inside a ScrollView. Our app relies heavily on custom views that are sometimes nested two or three levels deep. While the app does work fine overall, we see a massive spike in CPU usage in Instruments when accessibility features like VoiceOver are enabled. Those spikes never recover, so the app basically freezes and stays that way until force quit. We are in talks with a third-party service that uses accessibility features we want to use. Fortunately they have created a GitHub repository which recreates the issue we're facing. It would be greatly appreciated if someone could have a look at the code and tell us what the issue is, or if there's some kind of workaround. Here's the link to the repo: https://github.com/pendo-io/SwiftUI_Hang_Reproduction. Just to be clear, the issue is not directly related to the third-party SDK, but to the accessibility features used in conjunction with SwiftUI. As you can see in the repo the issue is reproducible without having the SDK included in the project. Thanks in advance
0
0
49
1d
NavigationBar iOS 26
Hi all, When navigating between two screens where the first uses .inline and the second .large title display mode, the NavigationBar shows visible resizing glitches during the push animation. This is especially noticeable when using a custom background color (e.g. yellow) via UINavigationBarAppearance or .toolbarBackground(Color.yellow, for: .navigationBar). I’m already using the same appearance for standard, scrollEdge, and compact, with configureWithOpaqueBackground(), but the issue remains. Is this a known UIKit or SwiftUI issue? Any recommended workaround? Thanks.
Topic: UI Frameworks SubTopic: SwiftUI
1
0
86
2d
List rows partially obscured by navigation bar briefly render fully opaque when switching tabs (iOS 26)
Overview In iOS 26, a List embedded in a NavigationStack inside a TabView exhibits a visual glitch when switching tabs. When the list is scrolled such that some rows are partially obscured by the navigation bar, the system correctly applies a fade/opacity effect to those rows. However, if the user switches to another tab while rows are in this partially obscured (faded) state, those rows briefly flash at full opacity during the tab transition before disappearing. This flash is visually distracting and appears to be inconsistent with the intended scroll-edge opacity behavior. The issue occurs only for rows partially obscured by the navigation bar. Rows partially obscured by the tab bar do not exhibit this flashing behavior. Steps to Reproduce: Run the attached minimal reproduction on iOS 26. Open the first tab. Scroll the list so that some rows are partially hidden behind the navigation bar (showing the native faded appearance). While rows are in this partially faded state, switch to the second tab. Observe that the faded rows briefly render fully opaque during the tab switch. Expected Behavior: Rows that are partially obscured by the navigation bar should maintain consistent opacity behavior during tab transitions, without flashing to full opacity. import SwiftUI @main struct NavBarReproApp: App { /// Minimal repro for iOS 26: /// - TabView with two tabs /// - First tab: NavigationStack + List /// - Scroll so some rows are partially behind the nav bar (faded) /// - Switch tabs: those partially-faded rows briefly flash fully opaque. Partially faded rows under the tab bar do not flash private let items = Array(0..<200).map { "Row \($0)" } var body: some Scene { WindowGroup { TabView { NavigationStack { List { ForEach(items, id: \.self) { item in Text(item) } } .navigationTitle("One") .navigationBarTitleDisplayMode(.inline) } .tabItem { Label("One", systemImage: "1.circle") } NavigationStack { Text("Second tab") .navigationTitle("Two") .navigationBarTitleDisplayMode(.inline) } .tabItem { Label("Two", systemImage: "2.circle") } } } } }
6
0
88
2d
.glassEffect() renders dark on device but works on simulator - TestFlight doesn't fix it
iOS 26 SwiftUI .glassEffect() renders dark/gray on physical device - TestFlight doesn't fix it .glassEffect() renders as dark/muddy gray on my physical iPhone instead of the light frosted glass like Apple Music's tab bar. What I've confirmed: Same code works perfectly on iOS Simulator Apple Music and other Apple apps show correct Liquid Glass on same device Brand new Xcode project with just .glassEffect() also renders dark TestFlight build (App Store signing) has the SAME problem - still dark/gray This rules out developer signing vs App Store signing as the cause What I've tried: Clean build, delete derived data, reinstall app Completely reinstalled Xcode All accessibility settings correct (Reduce Transparency OFF, Liquid Glass set to Clear) Disabled Metal diagnostics Debug and Release builds Added window configuration for Extended sRGB/P3 color space Added AppDelegate with configureWindowForLiquidGlass() Tried .preferredColorScheme(nil) Tried background animation to force "live" rendering Environment: iPhone 17 Pro, iOS 26.3 Xcode 26.2 macOS 26.3 The question: Why does .glassEffect() work for Apple's apps but not third party apps, even with App Store signing via TestFlight? What am I missing?
4
0
196
2d
Trailing closure passed to parameter of type 'Int' that does not accept a closure
I have TabView in ContentView and I want to add TabView for OnboardingView in OtherView, every things work, but it is throw error for TabView in OtherView like "Trailing closure passed to parameter of type 'Int' that does not accept a closure" I do not know why? Any idea? ContentView: struct TabView : View {       var body: some View{           VStack(spacing: 0){ ....... } OtherView:    VStack {     TabView {       ForEach(onboardingData) { onboardingItem in          OnboardingCard(onboardingItem: onboardingItem)       }   }   .tabViewStyle(PageTabViewStyle(indexDisplayMode: .automatic))   .indexViewStyle(PageIndexViewStyle (backgroundDisplayMode:   .always))   .foregroundColor(.white) }
9
1
6.6k
2d
SwiftUI ScrollView scrollTo not consistently scrolling to latest message
I am implementing an AI chat application and aiming to achieve ChatGPT-like behavior. Specifically, when a new message is sent, the ScrollView should automatically scroll to the top to display the latest message. I am currently using the scrollTo method for this purpose, but the behavior is inconsistent—sometimes it works as expected, and other times it does not. I’ve noticed that this issue has been reported in multiple places, which suggests it may be a known SwiftUI limitation. I’d like to know: Has this issue been fixed in recent SwiftUI versions, or does it still persist? If it still exists, is there a reliable solution or workaround that anyone can recommend?
2
0
111
3d
Button Style Glass Prominent Ignored on Menu When Used Inside ToolbarItem
When a Menu is placed inside a ToolbarItem, applying buttonStyle(.glassProminent) has no visible effect. The same modifier works correctly when a Button is used instead of a Menu inside the ToolbarItem. In that case, the button is rendered with the accent-colored background as expected. This suggests that Menu does not respect the .glassProminent button style when embedded in a ToolbarItem, even though other button types do. Code Example // Button with accent background color .toolbar { ToolbarItem(placement: .primaryAction) { Button(action: {}) .buttonStyle(.glassProminent) } } // Menu with internal button with no accent background color .toolbar { ToolbarItem(placement: .primaryAction) { Menu(...) { ... }.buttonStyle(.glassProminent) } }
Topic: UI Frameworks SubTopic: SwiftUI
1
0
38
3d
SwiftUI Performance vs identity
In SwiftUI, it is recommended not to store ViewBuilder closures in sub-views but instead evaluate them directly in init and store the result (example: https://www.youtube.com/watch?v=yXAQTIKR8fk). That has the advantage, as I understand it, that the closure doesn't need to be re-evaluated on every layout pass. On the other side, identity is a very important topic in SwiftUI to get the UI working properly. Now I have this generic view I'm using with a closure which is displayed in two places (HStack & VStack). Should I store the closure result and get the performance improvements, or evaluate it in place and get correct identities (if that is even an issue)? Simplified example: struct DynamicStack<Content: View>: View { @ViewBuilder var content: () -> Content var body: some View { ViewThatFits(in: .horizontal) { HStack { content() } VStack { content() } } } } vs struct DynamicStack<Content: View>: View { @ViewBuilder var content: Content var body: some View { ViewThatFits(in: .horizontal) { HStack { content } VStack { content } } } }
0
0
46
3d
Swipe to go back still broken with Zoom navigation transition.
When you use .navigationTransition(.zoom(sourceID: "placeholder", in: placehoder)) for navigation animation, going back using the swipe gesture is still very buggy on IOS26. I know it has been mentioned in other places like here: https://developer.apple.com/forums/thread/796805?answerId=856846022#856846022 but nothing seems to have been done to fix this issue. Here is a video showing the bug comparing when the back button is used vs swipe to go back: https://imgur.com/a/JgEusRH I wish there was a way to at least disable the swipe back gesture until this bug is fixed.
5
1
338
4d
SwiftUI subviews traverse issue
Our project include UIKIt and SwiftUI, and in some case, we need to traverse all subviews, for UIKit implement views, below code: func findView(byIdentifier identifier: String) -> UIView? { if self.accessibilityIdentifier == identifier { return self } for subview in subviews { if let found = subview.findView(byIdentifier: identifier) { return found } } return nil } works well, but for SwiftUI implement views, like below code: struct ContentView: View { var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) .accessibilityIdentifier("Image") Text("Hello, world!") .accessibilityIdentifier("Text") } .padding() } } it can not find subviews in the ContentView, and only a view with type: _UIHostingView<ModifiedContent<AnyView, RootModifier>> can be found, the Image and Text is not found; And because we have set a accessibilityIdentifier property, so we also try use: @MainActor var accessibilityElements: [Any]? { get set } to find sub node, but this accessibilityElements is not stable, we can find the Image and Text node in iOS26.1 system: [AX] level=3 AccessibilityNode @ 0x000000010280fb10 id=Image [AX] level=3 AccessibilityNode @ 0x000000010161fbf0 id=Text but can not find it in iOS26.0 and below system. Any suggestion in how to find SwiftUI subviews? thank you
Topic: UI Frameworks SubTopic: SwiftUI
2
0
146
4d
SwiftUI: AlignmentGuide in Overlay not working when in if block
Scenario A SwiftUI view has an overlay with alignment: .top, the content uses .alignmentGuide(.top) {} to adjust the placement. Issue When the content of the overlay is in an if-block, the alignment guide is not adjusted. Example code The example shows 2 views. Not working example, where the content is an if-block. Working example, where the content is not in an if-block Screenshot: https://github.com/simonnickel/FB15248296-SwiftUIAlignmentGuideInOverlayConditional/blob/main/screenshot.png Tested on - Xcode Version 16.0 RC (16A242) on iOS 18.0 Code // Not working .overlay(alignment: .top) { if true { // This line causes .alignmentGuide() to fail Text("Test") .alignmentGuide(.top, computeValue: { dimension in dimension[.bottom] }) } } // Working .overlay(alignment: .top) { Text("Test") .alignmentGuide(.top, computeValue: { dimension in dimension[.bottom] }) } Also created a Feedback: FB15248296 Example Project is here: https://github.com/simonnickel/FB15248296-SwiftUIAlignmentGuideInOverlayConditional/tree/main
2
2
464
4d
How to make fluid TabBar
Hey there guys, I'm new on SwiftUI and iOS Development world. How can I achieve a seamless TabBar transition in SwiftUI? Currently, when I programmatically hide the TabBar on a pushed view and swipe back to the previous view, there is a noticeable delay before the TabBar reappears. How can I make it appear instantly? Here is the link to the video https://streamable.com/3zz2o2 Thank you in advance
Topic: UI Frameworks SubTopic: SwiftUI
2
0
106
4d
Help with trailing closure errors
I am new to swiftui and have a very small project I am working on to practice passing data between views. I have this error on a form "Trailing closure passed to parameter of type 'FormStyleConfiguration' that does not accept a closure" If I comment the first section in the form then I get three errors in the ForEach. If anyone can help explain what is going on and what steps I could take to determine where the problem is coming from I would appreciate the help. This is the model I created: import Observation import SwiftUI @Model final class Client { var id = UUID() var name: String var location: String var selectedJob: Person init(id: UUID = UUID(), name: String, location: String, selectedJob: Person) { self.id = id self.name = name self.location = location self.selectedJob = selectedJob } } extension Client { enum Person: String, CaseIterable, Codable { case homeOwner = "Home Owner" case contractor = "Contractor" case designer = "Designer" } } @Model class Enclosure { var id = UUID() var room: String = "" var unitType: String = "" init(id: UUID = UUID(), room: String, unitType: String) { self.id = id self.room = room self.unitType = unitType } } This is the detail view where the error is happening: import SwiftData import SwiftUI struct DetailView: View { @Environment(\.modelContext) private var modelContext @Environment(\.dismiss) private var dismiss @Query(sort: \Enclosure.room, order: .forward, animation: .default) private var enclosures: [Enclosure] @State private var showingAddEnclosure = false @State private var showingAddMirror = false @State private var name: String = "" @State private var location: String = "" @State private var selectedJob = Client.Person.homeOwner @State var clients: Client var body: some View { NavigationStack { Form { Section("Details") { TextField("Full Name", text: Client.$name) TextField("Location", text: Client.location) Picker("Job Type", selection: $selectedJob) { ForEach(Client.Person.allCases, id: \.self) { selected in Text(selected.rawValue).tag(selected) } } } Section("Enclosures") { List { ForEach($clients.enclosures) { enclosure in NavigationLink(destination: EnclosureDetailView()) { VStack { Text(enclosure.room) Text(enclosure.unitType) } } .swipeActions { Button("Delete", role: .destructive) { modelContext.delete(enclosure) } } } } } } .navigationTitle("Project Details") .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .topBarTrailing) { Menu { Button { showingAddEnclosure.toggle() } label: { Text("Add Enclosure") } Button { showingAddMirror.toggle() } label: { Text("Add Mirror") } } label: { Label("Add", systemImage: "ellipsis.circle") } } } .sheet(isPresented: $showingAddEnclosure) { EnclosureView() } .sheet(isPresented: $showingAddMirror) { EnclosureView() } } } }
3
0
965
5d