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
765
Jun ’25
Incorrect color for inline navigation bar title when dark mode AND reduce transparency ON.
I reproduced this in iPhone 17 and iPhone 17 Pro simulators running iOS 26.0 import SwiftUI struct ContentView: View { var body: some View { NavigationStack { ScrollView { VStack { ForEach(0..<100) { i in Text("Row \(i)") .frame(maxWidth: .infinity) } } .padding() } .navigationTitle("Toolbar Test") .navigationBarTitleDisplayMode(.inline) // or .automatic } } } Run this code in a vanilla SwiftUI app. Toggle the appearance to dark mode. In the simulator's Settings app -> Accessibility -> Display and Text Size. Turn ON "Reduce Transparency". Go back to the app and start scrolling if you need to. You can observe that the title is unreadable - black text on a black navigation bar.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
2
0
64
22m
How To Position Controls With SwiftUI
I am coming from C#, where Forms and Controls are placed similar to Swift Storyboards. I have been trying to learn Storyboards, but keep running across tutorials regarding SwiftUI, and Storyboard examples are few. So the question becomes, "how do I position controls on a Form using SwiftUI?" See the example below. I have run across many videos that use either horizontal or vertical positioning of controls, but these examples are usually very simple, with items occupying only the center portion of the screen. I get stuck on examples that are more complicated. The example below only shows the controls for the upper part of a Form, with some type of textbox (Viewform) below making up the rest of the Form. How does one make more complicated placement of controls with SwiftUI?
5
0
107
1h
SwiftUI Picker layout under MacOS26
Prior to MacOS 26, Multiple Pickers could be laid out with a uniform width. For example: struct LayoutExample: View { let fruits = ["apple", "banana", "orange", "kiwi"] let veg = ["carrot", "cauliflower", "peas", "Floccinaucinihilipilification Cucurbitaceae"] @State private var selectedFruit: String = "kiwi" @State private var selectedVeg: String = "carrot" var body: some View { VStack(alignment: .leading) { Picker(selection: $selectedFruit) { ForEach(fruits, id: \.self, content: Text.init) } label: { Text("Fruity choice") .frame(width: 150, alignment: .trailing) } .frame(width: 300) Picker(selection: $selectedVeg) { ForEach(veg, id: \.self, content: Text.init) } label: { Text("Veg") .frame(width: 150, alignment: .trailing) } .frame(width: 300) } } } Renders like this, prior to MacOS26: But now looks like this under MacOS 26: Is there anyway to control the size of the picker selection in MacOS 26?
1
0
28
3h
tvOS 26 Top shelf's playbackProgress is broken
Here is a minimal code private func createItem(from movie: Movie, showProgress: Bool, imageType: ImageType) -> TVTopShelfSectionedItem { let item = TVTopShelfSectionedItem(identifier: movie.id) // Set title for the item item.title = movie.title switch imageType { case .landscape: item.imageShape = .hdtv // HDTV shape for landscape/backdrop images if let backdropUrl = movie.backdropUrl, let url = URL(string: backdropUrl) { item.setImageURL(url, for: .screenScale2x) } case .poster: item.imageShape = .poster // Poster shape for poster images if let posterUrl = movie.posterUrl, let url = URL(string: posterUrl) { item.setImageURL(url, for: .screenScale2x) } } if showProgress { item.playbackProgress = 0.5 } return item } As you can see the progress bar is pushed to the bottom. There is no padding around it. Am I doing something wrong or this is bug in the framework?
0
0
37
4h
Source view disappearing when interrupting a zoom navigation transition
When I use the .zoom transition in a navigation stack, I get a glitch when interrupting the animation by swiping back before it completes. When doing this, the source view disappears. I can still tap it to trigger the navigation again, but its not visible on screen. This seems to be a regression in iOS 26, as it works as expected when testing on iOS 18. Has someone else seen this issue and found a workaround? Is it possible to disable interrupting the transition? Filed a feedback on the issue FB19601591 Screen recording: https://share.icloud.com/photos/04cio3fEcbR6u64PAgxuS2CLQ Example code @State var showDetail = false @Namespace var namespace var body: some View { NavigationStack { ScrollView { showDetailButton } .navigationTitle("Title") .navigationBarTitleDisplayMode(.inline) .navigationDestination(isPresented: $showDetail) { Text("Detail") .navigationTransition(.zoom(sourceID: "zoom", in: namespace)) } } } var showDetailButton: some View { Button { showDetail = true } label: { Text("Show detail") .padding() .background(.green) .matchedTransitionSource(id: "zoom", in: namespace) } } }
Topic: UI Frameworks SubTopic: SwiftUI
10
12
329
9h
Looking for advice on app architecture
I have an existing Mac app which has evolved through over twenty years of development. It is currently written in a mixture of C++ and Objective-C, with a bit of C and Swift in a few places. For a few years now, I have been tinkering with replacing the UI with SwiftUI. The model has been completely rewritten in Swift and works fine. After a few tries, no version has been working acceptably, so I'm thinking that I need to rethink the architecture. The UI consists of a window with a master-detail view. The detail view is what users spend most of their time with. It contains a lot of subviews, around 100 typically. Keyboard events affect the display, so I've had a dedicated data structure to hold the state that is needed for displaying all the subviews. Using Instruments, I see that the view seems to recreate the subviews three times per keyboard event, so I'm clearly doing something wrong. A second factor is that there are a couple of dozen commands that are applicable to the detail view, driven either by menu items, keyboard shortcut, or toolbar button. Adding all of those to the view makes for a massive SwiftUI View, which seems unlikely to be good practice. The current implementation has the controller class broken up with categories, but still they are big classes. Most SwiftUI stuff on the web is iOS-oriented, and typically has a focus on fairly simple apps, so the whole topic of dealing with menu commands doesn't get a lot of coverage, so I've been doing all that through my own solutions, which are probably nothing like optimal. What I've been able to find is not particularly helpful for a full-fledged application like mine, so I'm looking for advice on how to structure the app. The existing one is largely MVC, but I've tried a similar approach and a shot at MVVM, but I'm not getting good results so far. So, pointers, places I can read more, or samples of real-world apps is what I'm after. Anyone?
Topic: UI Frameworks SubTopic: SwiftUI Tags:
1
0
40
12h
iOS 26 navigationTransition .zoom issue
When I dismiss a view presented with .navigationTransition(.zoom), the source view gets a weird background (black or white depending on the appearance) for a couple of seconds, and then it disappears. Here’s a simple code example. import SwiftUI struct NavigationTransition: View { @Namespace private var namespace @State private var isSecondViewPresented = false var body: some View { NavigationStack { ZStack { DetailView(namespace: namespace) .onTapGesture { isSecondViewPresented = true } } .fullScreenCover(isPresented: $isSecondViewPresented) { SecondView() .navigationTransition(.zoom(sourceID: "world", in: namespace)) } } } } struct DetailView: View { var namespace: Namespace.ID var body: some View { ZStack { Color.blue Text("Hello World!") .foregroundStyle(.white) .matchedTransitionSource(id: "world", in: namespace) } .ignoresSafeArea() } } struct SecondView: View { var body: some View { ZStack { Color.green Image(systemName: "globe") .foregroundStyle(Color.red) } .ignoresSafeArea() } } #Preview { NavigationTransition() }
5
4
191
12h
Bug Report: SwiftUI @State Array Assignment Fails to Trigger UI Updates. Presumably when lengths of the old and new arrays are the same.
Environment: — Xcode Version: [Current version] — iOS Version: [Target iOS version] — Swift Version: 6.0.3 — Platform: iOS Summary: Direct assignment of new arrays to @State properties sometimes fails to trigger UI updates, even when the arrays contain different data. The assignment appears to succeed in code but the UI continues to display stale data. Presumably when lengths of both arrays are the same. Assigning first empty array and then the new array fixed the issue. Expected Behavior: When assigning a new array to a @State property (self.stateArray = newArray), SwiftUI should detect the change and update the UI to reflect the new data. Actual Behavior: The assignment self.stateArray = newArray executes without error, but the UI continues to display data from the previous array. Debugging shows that self._stateArray (the underlying property wrapper) retains the old data despite the assignment. Minimal Reproduction Case: struct ContentView: View { @State private var items: [String] = ["Old Item"] var body: some View { VStack { ForEach(items, id: \.self) { item in Text(item) } Button("Update Items") { // This assignment may not trigger UI update self.items = ["New Item", "Another Item"] // Workaround: Clear first, then assign // self.items = [] // self.items = ["New Item", "Another Item"] } } } } Workaround: Force the state update by clearing the array before assignment: self.items = [] // Clear first self.items = newArray // Then assign new data Additional Context: — This issue was discovered in a production app where item data loaded from cache wasn't updating the UI. — The same data loading pattern worked in one view (which is modal and doesn't reload data) but failed in another (which needs to be refreshed). — Console logs showed fresh data was loaded but UI displayed stale data. — Debugger showed self._items instead of self.items, which might suggest property wrapper issues. Impact: This causes significant user experience issues where the UI doesn't reflect the actual application state, leading to confusion and apparent data inconsistency. Request: Please investigate why direct @State array assignment sometimes fails and consider fixing the underlying cause, or at minimum document this behavior and recommended workarounds.
1
0
65
22h
Trouble with contextMenu previewing high resolution images
When using a contextMenu in SwiftUI to show a preview of a PHAsset’s full-size image via PHCachingImageManager.requestImage(), memory usage increases with each image preview interaction. The memory is not released, leading to eventual app crash due to memory exhaustion. The thumbnail loads and behaves as expected, but each call to fetch the full-size image (1000x1000) for the contextMenu preview does not release memory, even after cancelImageRequest() is called and fullSizePreviewImage is set to nil. The issue seems to stem from the contextMenu lifecycle behavior, it triggers .onAppear unexpectedly, and the full-size image is repeatedly fetched without releasing the previously loaded images. The question is, where do I request to the get the full-size image to show it in the context menu preview? STEPS TO REPRODUCE 1/ Create a SwiftUI LazyVGrid displaying many PHAsset thumbnails using PHCachingImageManager. 2/ Add a .contextMenu to each thumbnail button with: .onAppear that triggers requestImage() for a high-resolution preview. .onDisappear that calls cancelImageRequest() and sets the image @State to nil. 3/ Tap on several image previews 4/ Monitor memory usage as it increases and eventually crashes
1
0
34
1d
tabViewBottomAccessory AttributeGraph cycles, broken behavior of views participating in cycles
Seemingly innocuous contents passed to tabViewBottomAccessory can trigger inscrutable AttributeGraph cycles, which can then cause unexplained broken behavior of views that may be participating in these cycles. These cycles can be introduced by adding common elements to the tabViewBottomAccessory view hierarchy, like Slider, Button, Toggle, and even things simple if statements surrounding Text elements. These cycles can even also be triggered in a manner that causes the tabViewBottomAccessoryPlacement Environment value to be nil, which can then cause views that depend on this value to render incorrectly or not at all. The errors logged to the Xcode console are of the form: === AttributeGraph: cycle detected through attribute 29528 === === AttributeGraph: cycle detected through attribute 324264 === No further information about this attribute is available in any public Xcode tools. Environment XCode Version 26.0 (17A324) iOS 26.0 (23A343) Steps to reproduce Run the sample above in Simulator Observe no AttributeGraph cycles in Xcode console. Uncomment any of the commented out examples in SliderView.body Observe Xcode console for AttributeGraph cycle messages. Observe glitchy animation behavior Expected Behavior No AttributeGraph cycle diagnostics for ordinary state changes. tabViewBottomAccessoryPlacement always present (non-nil) while accessory is attached. Dependent views update consistently. Errors logged to the Console would help guide me towards a resolution Impact Undermines confidence in adopting tabViewBottomAccessory. Hard to debug: cycle traces are opaque and environment silently degrades (becomes nil) instead of asserting. Nearly shipped a UI where accessory layout fails sporadically. What would help Underlying fix to prevent cycles for ordinary accessory content mutations. Guarantee (or documented contract) that tabViewBottomAccessoryPlacement is never nil while accessory is active, or an assert if invariants break. Option to enable detailed environment propagation trace when a cycle is detected. Symbolic source identifiers in cycle backtraces. Documentation note on current limitations (if certain view types are not yet supported in accessory regions).
Topic: UI Frameworks SubTopic: SwiftUI
1
2
81
1d
Custom SF Symbols with badges not vertically centered in SwiftUI buttons
[Also submitted as FB20225387] When using a custom SF Symbol that combines a base symbol with a badge, the symbol doesn’t stay vertically centered when displayed in code. The vertical alignment shifts based on the Y offset of the badge. There are two problems with this: The base element shouldn’t move vertically when a badge is added—the badge is meant to add to the symbol, not change its alignment. The badge position should be consistent with system-provided badged symbols, where badges always appear in a predictable spot relative to the corner they're in (usually at X,Y offsets of 90% or 10%). Neither of these behaviors match what’s expected, leading to inconsistent and misaligned symbols in the UI. Screenshot of Problem The ellipsis shifts vertically whenever the badge Y offset is set to anything other than 50%. Even at a 90/10 offset, it still doesn’t align with the badge position of the system "envelope.badge" symbol. SF Symbols Export This seem to be a SwiftUI issue since both the export from SF Symbols is correctly centered: Xcode Assets Preview And it's also correct in the Xcode Assets preview: Steps to Repro In SF Symbols, create a custom symbol of "ellipsis" (right-click and Duplicate as Custom Symbol) Combine it with the "badge" component (select Custom Symbols, select the newly-created "custom.ellipsis", then right-click and Combine Symbol with Component…) Change the badge's Y Offset to 10%. Export the symbol and add it to your Xcode asset catalog. In Xcode, display the symbol inside a Button using Image(“custom.ellipsis.badge”). Add a couple more buttons separated by spacers, using system images of "ellipsis" and "app.badge". Compare the "custom.ellipsis.badge" button to the two system symbol buttons. Expected The combined symbol remains vertically centered, matching the alignment shown in both the SF Symbols export window and the Xcode asset catalog thumbnails. Actual The base symbol (e.g., the ellipsis portion) shifts vertically based on the Y offset of the badge element. This causes visual misalignment when displayed in SwiftUI toolbars or other layouts. Also included the system “envelope.badge” icon to show where a 90%, 10% badge offset should be located. System Info SF Symbols Version 7.0 (114) Xcode Version 26.0 (17A321) macOS 15.6.1 (24G90) iOS 26.0 (23A340)
1
0
217
1d
CarPlay app not receiving data updates when iPhone screen is locked
We are building a CarPlay app and have run into an issue with data updates. When the app is running on the CarPlay display and the iPhone screen is locked, no data updates are shown on the CarPlay screen. As soon as the phone is unlocked, the data updates appear instantly on the CarPlay display. Has anyone encountered this behavior before? Is there a specific setting, entitlement, or background mode we need to enable in order to ensure the CarPlay app continues to receive and display data while the iPhone is locked? Any guidance would be greatly appreciated.
2
2
137
1d
I need help
I am trying to learn to write swift. I am very proficient MS VB, which I have been using for almost 20 years. The Book I am learning from is: SwiftUI for Masterminds. I have got to chapter 7 with no problem. The exercise I am having a problem with Listing 7-5. The error I am getting is: Thread 1: Fatal error: No Observable object of type ApplicationData found. A View.environmentObject(_:) for ApplicationData may be missing as an ancestor of this view. I have spent the last 2 days rechecking my code. The MacBook I am using was purchased in May this year, is 16 in, M4 Max chip, 128 G ram. Firstly I want to thank you for reading this post. Secondly is there a better book to learn SwiftUI. Regards Terry Harrison
Topic: UI Frameworks SubTopic: SwiftUI Tags:
2
0
158
1d
I need help
I am trying to learn to write swift. I am very proficient MS VB, which I have been using for almost 20 years. The Book I am learning from is: SwiftUI for Masterminds by J.D Gauchat. I have got to chapter 7 with no problem. The exercise I am having a problem with Listing 7-5. The error I am getting is: Thread 1: Fatal error: No Observable object of type ApplicationData found. A View.environmentObject(_:) for ApplicationData may be missing as an ancestor of this view. I have spent the last 2 days rechecking my code. The MacBook I am using was purchased in May this year, is 16 inch, Max 4 pro chip with 128 G Ram I am seeking help here as a last resort, I understand everybody is busy. The main issue I have with the book is the author assumes you know as much as he does. As I stated, I am very proficient MS VB Firstly Is the SwiftUI for Masterminds to advanced for? Secondly What is the best book to start with and then move on to SwiftUI for Masterminds. Thirdly I thank you for reading my first post here. Regards Terry Harrison
Topic: UI Frameworks SubTopic: SwiftUI
3
0
137
1d
Learn to write SwiftUI
I am trying to learn to write swift. I am very proficient MS VB, which I have been using for almost 20 years. The Book I am learning from is: SwiftUI for Masterminds. I have got to chapter 7 with no problem. The exercise I am having a problem with Listing 7-5. The error I am getting is: Thread 1: Fatal error: No Observable object of type ApplicationData found. A View.environmentObject(_:) for ApplicationData may be missing as an ancestor of this view. I have spent the last 2 days rechecking my code. The MacBook I am using was purchased in May this year, is 16 in, M4 Max chip, 128 G ram. Firstly I want to thank you for reading this post. Secondly is there a better book to learn SwiftUI. Regards Terry Harrison
Topic: UI Frameworks SubTopic: SwiftUI
1
0
393
1d