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

Force a locale from string catalog
I'm writing an iOS app that shares content with buddies. So my app will run in one language but the shared content will use the locale configured for the buddy. I found this Apple documentation which suggests that locale: (Locale(identifier: is the solution. Apple Documentation But I can't get it to work. Here's sample code. struct LocalizationDemoView: View { @State var isEnglish = true var body: some View { var myLocale: String { isEnglish ? "en": "de" } VStack { Toggle("Switch language", isOn: $isEnglish).frame(maxWidth: 200) HStack { Text("\(myLocale): ") Text(String(localized: "Hello world!", locale: (Locale(identifier: myLocale)), comment: "To share")) } } } } And here's the excerpt from the string catalog: { "sourceLanguage" : "en", "strings" : { "Hello world!" : { "comment" : "To share", "localizations" : { "de" : { "stringUnit" : { "state" : "translated", "value" : "🇩🇪 Moin Welt!" } }, "en" : { "stringUnit" : { "state" : "translated", "value" : "🇬🇧 Hello world!" } } } } } } Has Apple reduced support for string catalogs or is my code wrong? Xcode 16.4 compiled on MacOS 15.6.1, device iOS 18.6.2
4
0
200
2w
Seeing some behaviour in Swift that I don't understand...
It's related to the passByValue nature of structs. In the sample code below, I'm displaying a list of structs (and I can add instances to my list using Int.random(1..<3) to pick one of two possible predefined versions of the struct). I also have a detail view that can modify the details of a single struct. However when I run this code, it will instead modify all the instances (ie either Sunday or Monday) in my list. To see this behaviour, run the following code and: tap New Trigger enough times that there are multiple of at least one of the sunday/monday triggers tap one of the matching trigger rows modify either the day, or the int expected: only one of the rows will reflect the edit actual: all the matching instances will be updated. This suggests to me that my Sunday and Monday static instances are being passed by reference when they get added to the array. But I had thought structs were strictly pass by value. What am I missing? thanks in advance for any wisdom, Mike struct ContentView: View { @State var fetchTriggers: [FetchTrigger] = [] var body: some View { NavigationView { VStack { Button("New Trigger") { fetchTriggers.append(Int.random(in: 1..<3) == 1 ? .sunMorning : .monEvening) } List($fetchTriggers) { fetchTrigger in NavigationLink(destination: FetchTriggerDetailView(fetchTrigger: fetchTrigger) .navigationBarTitle("Back", displayMode: .inline)) { Text(fetchTrigger.wrappedValue.description) .padding() } } } } } } struct FetchTrigger: Identifiable { static let monEvening: FetchTrigger = .init(dayOfWeek: .monday, hour: 6) static let sunMorning: FetchTrigger = .init(dayOfWeek: .sunday, hour: 3) let id = UUID() enum DayOfWeek: Int, Codable, CaseIterable, Identifiable { var id: Int { self.rawValue } case sunday = 1 case monday case tuesday var description: String { switch self { case .sunday: return "Sunday" case .monday: return "Monday" case .tuesday: return "Tuesday" } } } var dayOfWeek: DayOfWeek var hour: Int var description: String { "\(dayOfWeek.description), \(hour):00" } } struct FetchTriggerDetailView: View { @Binding var fetchTrigger: FetchTrigger var body: some View { HStack { Picker("", selection: $fetchTrigger.dayOfWeek) { ForEach(FetchTrigger.DayOfWeek.allCases) { dayOfWeek in Text(dayOfWeek.description) .tag(dayOfWeek) } } Picker("", selection: $fetchTrigger.hour) { ForEach(1...12, id: \.self) { number in Text("\(number)") .tag(number) } } } } }
Topic: UI Frameworks SubTopic: SwiftUI Tags:
1
0
181
2w
Menu view flashes white before closing when device is set to dark appearance
Feedback ID: FB19846667 When dismissing a Menu view when the device is set to dark appearance, there is a flash of lightness that is distracting and feels unnatural. This becomes an issue for apps that rely on the user interacting with Menu views often. When using the overflow menu on a toolbar, the effect of dismissing the menu is a lot more natural and there is less flashing. I expect a similar visual effect when creating Menu views outside of a toolbar. Has anyone found a way around this somehow? Comparison between dismissing a menu and a toolbar overflow: https://www.youtube.com/shorts/H2gUQOwos3Y Slowed down version of dismissing a menu with a visible light flash: https://www.youtube.com/shorts/MBCCkK-GfqY
0
0
129
2w
iOS 26 @FocusState Doesn't Work If TextField Is In Toolbar
When I add a TextField with @FocusState to a toolbar, I noticed that setting focus = false doesn't cause the form to lose focus If I move the TextField out of the toolbar setting focus = false works fine. How can I unfocus the text field when the cancel button is tapped? Minimal example tested on Xcode Version 26.0 beta 6 (17A5305f): import SwiftUI struct ContentView: View { @State private var text: String = "" @FocusState private var focus: Bool var body: some View { NavigationStack { List { Text("Test List") } .toolbar { ToolbarItem(placement: .bottomBar) { TextField("Test", text: $text) .padding(.horizontal) .focused($focus) } ToolbarItem(placement: .bottomBar) { Button(role: .cancel) { focus = false // THIS DOESN'T WORK! } } } } } } #Preview { ContentView() }```
0
1
180
2w
How do you observe the count of records in a Swift Data relationship?
What is the correct way to track the number of items in a relationship using SwiftData and SwiftUI? Imagine a macOS application with a sidebar that lists Folders and Tags. An Item can belong to a Folder and have many Tags. In the sidebar, I want to show the name of the Folder or Tag along with the number of Items in it. I feel like I'm missing something obvious within SwiftData to wire this up such that my SwiftUI views correctly updated whenever the underlying modelContext is updated. // The basic schema @Model final class Item { var name = "Untitled Item" var folder: Folder? = nil var tags: [Tag] = [] } @Model final class Folder { var name = "Untitled Folder" var items: [Item] = [] } @Model final class Tag { var name = "Untitled Tag" var items: [Item] = [] } // A SwiftUI view to show a Folder. struct FolderRowView: View { let folder: Folder // Should I use an @Query here?? // @Query var items: [Item] var body: some View { HStack { Text(folder.name) Spacer() Text(folder.items.count.formatted()) } } } The above code works, once, but if I then add a new Item to that Folder, then this SwiftUI view does not update. I can make it work if I use an @Query with an #Predicate but even then I'm not quite sure how the #Predicate is supposed to be written. (And it seems excessive to have an @Query on every single row, given how many there could be.) struct FolderView: View { @Query private var items: [Item] private var folder: Folder init(folder: Folder) { self.folder = folder // I've read online that this needs to be captured outside the Predicate? let identifier = folder.persistentModelID _items = Query(filter: #Predicate { link in // Is this syntax correct? The results seem inconsistent in my app... if let folder = link.folder { return folder.persistentModelID == identifier } else { return false } }) } var body: some View { HStack { Text(folder.name) Spacer() // This mostly works. Text(links.count.formatted()) } } } As I try to integrate SwiftData and SwiftUI into a traditional macOS app with a sidebar, content view and inspector I'm finding it challenging to understand how to wire everything up. In this particular example, tracking the count, is there a "correct" way to handle this?
1
0
111
2w
`Invalid frame dimension (negative or non-finite)` on iPhone 12 mini
Hi everyone, I’m encountering the following error when displaying a TextField inside a Form together with a ToolbarItem(placement: .keyboard): Invalid frame dimension (negative or non-finite). Environment This issue reproduces on iPhone 12 mini (iOS 18.6). The same code does not reproduce on iPhone 15. I confirmed that explicitly constraining the size of the TextField or Text with .frame(width:height:) does not resolve the issue. Minimal Reproducible Example import SwiftUI struct Test: View { @State var value: Int = 0 var body: some View { Form { TextField("0", value: $value, format: .number) } .toolbar { ToolbarItem(placement: .keyboard) { Text("Close") } } } } Has anyone else encountered this issue? Is this a known bug, or is there a recommended workaround for devices with smaller screen widths such as the iPhone 12 mini? Thanks in advance for your help! Best regards, Naoya Ozawa
Topic: UI Frameworks SubTopic: SwiftUI
0
0
50
2w
contentMargins (with .horizontal) creates a visual bug with the sidebar when using a NavigationSplitView in iOS 26 beta 7
FB: FB19828741 Maybe I am doing something wrong with the new LiquidGlass sidebar using iPadOS 26 Beta 7, but when using this code, in stead of the List being centered between the sidebar and the rest of the screen, the cell itself extends beneath the sidebar but the content stays clear of the sidebar, giving a weird visual effect. Not my expected behavior at least. Any ideas? Or just a bug? import SwiftUI struct ContentView: View { var body: some View { NavigationSplitView { Text("Test") } detail: { List { Text("ContentMargin") } .contentMargins(.horizontal, 100.0) } } } #Preview { ContentView() } This was on iPad OS 18:
0
0
63
2w
How to get view backgrounds for widget with clear or tinted rendering
The calendar widget and buttons shows a lightened / material background behind some content when the widget is in clear / tinted mode (example here: https://developer.apple.com/videos/play/wwdc2025/278?time=72). How can this be done? I tried applying a material and glass background to a view using the .background(...) modifier, but the background is made white. Text("Hello") .padding() .background { ContainerRelativeShape() .fill(.thinMaterial) } Text("Hello") .padding() .background { ContainerRelativeShape() .glassEffect() } Is this not supported, a bug, or am I doing something wrong?
1
1
94
2w
.textContentType(.emailAddress) does not work as expected
The following code: struct ContentView: View { @State private var email = "" var body: some View { VStack { TextField("email", text: $email) .textContentType(.emailAddress) } } } does not work as expected. What I expected is to run the app and have it suggest my actual email when I click into the field. Instead what it does is display "Hide My Email" twice. Selecting the first "Hide My Email" pastes the actual text "Hide My Email" into the field, the second one brings up an iCloud sheet to select a random email. Trying some suggestions online for .emailAddress in general not working does not change anything: TextField("Email", text: $email) .textFieldStyle(RoundedBorderTextFieldStyle()) .textContentType(.emailAddress) .keyboardType(.emailAddress) .autocorrectionDisabled() .disableAutocorrection(true) .textInputAutocapitalization(.never)
Topic: UI Frameworks SubTopic: SwiftUI
1
0
110
2w
Custom view interactive glass effect clipped by view bounds when tapped
Take this piece of code for example: Menu { ... } label: { Image(systemName: "ellipsis.circle") .resizable() .foregroundStyle(Color.primary) .frame(width: 24, height: 24) .contentShape(.circle) .padding(.spacing8) .glassEffect(.regular.interactive(), in: .circle) } .tint(nil) When tapped, the interactive liquid glass effect expands in response, but the expanded glass is then clipped by the original bounds of the view. In this example, the button would briefly show up as a highlighted square due to the clipping. If I add enough padding around the Menu's label, the expanded glass effect is be able to show unclipped, but this feels like a hack. Is this a bug in the framework, or am I doing something wrong? I have submitted FB19801519 with screen recording and demo project.
0
0
80
2w
Should ModelActor be used to populate a view?
I'm working with SwiftData and SwiftUI and it's not clear to me if it is good practice to have a @ModelActor directly populate a SwiftUI view. For example when having to combine manual lab results and clinial results from HealthKit. The Clinical lab results are an async operation: @ModelActor actor LabResultsManager { func fetchLabResultsWithHealthKit() async throws -> [LabResultDto] { let manualEntries = try modelContext.fetch(FetchDescriptor<LabResult>()) let clinicalLabs = (try? await HealthKitService.getLabResults()) ?? [] return (manualEntries + clinicalLabs).sorted { $0.date > $1.date }.map { return LabResultDto(from: $0) } } } struct ContentView: View { @State private var labResults: [LabResultDto] = [] var body: some View { List(labResults, id: \.id) { result in VStack(alignment: .leading) { Text(result.testName) Text(result.date, style: .date) } } .task { do { let labManager = LabResultsManager() labResults = try await labManager.fetchLabResultsWithHealthKit() } catch { // Handle error } } } } EDIT: I have a few views that would want to use these labResults so I need an implementation that can be reused. Having to fetch and combine in each view will not be good practice. Can I pass a modelContext to a viewModel?
4
0
151
2w
Display segmented control in iOS 26 with the previous rounded rectangle style
The default style for a segmented picker in iOS 26 is now a capsule shape. Is it possible to get back the previous rounded rectangle shape? In SwiftUI I have tried using the clipShape, containerShape, and background modifiers, applying a RoundedRectangle shape with a corner radius, to no avail. In UIKit I have tried to adjust the corner configuration for the UISegmentedControl, also to no avail. Am I missing something really obvious or is it impossible to change the style here? 🤔
2
0
148
2w
iPadOS 26 Disable "open recent"
How can I remove the "recents" section from long-pressing on my app icon? I've added the following to my AppDelegate, which removes it from the top MenuBar, but not from the app icon context menu. My app has registered a custom filetype, but it is not a document based app. Opening files imports them into the app's user library, and so does not make sense to have a "recents" list. override func buildMenu(with builder: any UIMenuBuilder) { super.buildMenu(with: builder) builder.remove(menu: .openRecent) }
1
0
156
3w
iOS 26 Home Screen Widgets Color Rendering Issue
Hi everyone! I've noticed a color rendering issue with Home Screen widgets on iOS 26: the colors displayed in widgets are inconsistent with those shown inside the app. At first, I suspected this might be caused by differences in color spaces, but even after explicitly specifying the color space for SwiftUI.Color or UIColor, the widget colors remain incorrect. Steps to reproduce: Create a new iOS project in Xcode 26 beta 6. Add a new Widget Extension target. Use the following Widget view code: struct MyWidgets: Widget { let kind: String = "MyWidgets" var body: some WidgetConfiguration { StaticConfiguration(kind: kind, provider: Provider()) { entry in let white = Color(.sRGB, red: 1, green: 1, blue: 1) let veryLightGray = Color(.sRGB, red: 0.96, green: 0.96, blue: 0.96) let lightGray = Color(.sRGB, red: 0.9, green: 0.9, blue: 0.9) VStack(spacing: 0) { Rectangle() .foregroundStyle(veryLightGray) // 👈 Rectangle() .foregroundStyle(lightGray) // 👈 } .containerBackground(white, for: .widget) // 👈 } .configurationDisplayName("My Widget") } } ⬆️ In-app, the colors are correct: the top block is a very light gray (white=0.96)✅, and the bottom block is a regular gray (white=0.90)✅. However, on the Home Screen widget, the result is as follows: ⬆️ The top light gray block blends completely into the white background and is indistinguishable; the bottom gray block also appears lighter than it does in-app ❌. This issue occurs both on the simulator and on real devices. (Interestingly, the colors are correct in the Xcode Preview.) Whether I declare colors in code (SwiftUI.Color or UIColor) or in the Asset Catalog, the widget's color rendering does not match expectations. What's even stranger is that if I add an extra pure white block (white=1.0) to the view, it immediately affects all the colors in the widget: This whole behavior makes it very difficult to set accurate colors for widgets on iOS 26. While it seems related to glass effect rendering and color space handling, I still feel there might be a bug in the implementation.
1
0
87
3w
How to Start with Default Apple Maps Functionality in iOS 18+
Hi everyone, I’m building an iOS 18+ app in Xcode where Apple Maps is central. My goal is to start with the default Apple Maps experience (map view, search bar, pins, directions sheet, etc.) and then customize it for my project. I tried coding it from scratch using MapKit and SwiftUI, but I wasn’t able to get full parity with the basic features of the Maps app. My questions: Is there any sample project, template, or reference that provides the default Apple Maps functionality (views + interactions) as a baseline? Can I copy these into my Xcode project and then extend/customize them? If not, what’s the recommended best practice to get as close as possible to the native Maps app before adding my own features? Any guidance, sample code, or documentation links would be greatly appreciated.
1
0
89
3w
iOS 26, SwiftUI .sheet Background Color has Gray/Green Tint on iPad
On iPadOS 26 (up to beta 7), .sheet backgrounds have a dark green tint on Dark Mode and a gray tint on Light Mode. This is clearly noticeable on both the Canvas/Simulator and a physical device. Here's a sample View that shows the issue: import SwiftUI struct ContentView: View { @State private var isPresenting: Bool = false var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") Button("Show Sheet") { isPresenting.toggle() } } .sheet(isPresented: $isPresenting) { VStack { HStack { Spacer() Button("Cancel", systemImage: "xmark.circle.fill") { } .foregroundStyle(.secondary) .labelStyle(.iconOnly) .buttonStyle(.plain) .contentShape(.circle) } TabView { Tab("Tab 1", systemImage: "cart") { Text("Hello, tab 1") } Tab("Tab 2", systemImage: "cart") { Text("Hello, tab 2") } } } .scenePadding() } .padding() .preferredColorScheme(.dark) } } #Preview { ContentView() } Is this the expected behavior with the new OS? Anyone else seeing this?
Topic: UI Frameworks SubTopic: SwiftUI
1
0
150
3w
How can I connect NSTableCellView.textField to a SwiftUI view?
When using NSTableView or NSOutlineView, if you use an NSTableCellView and wire up the .imageView and .textField properties then you get some "free" behaviour with respect to styling and sizing of those fields. (ex: They reflect the user's preferred "Sidebar Icon Size" as selected in Settings. ) If I'm using a SwiftUI View inside an NSTableCellView, is there any way to connect a Text or Image to those properties? Consider the following pseudo code: struct MyCellView: View { let text: String let url: URL? var body: some View { HStack { Image(...) // How to indicate this is .imageView? Text(...) // How to indicate this is .textField? } } } final class MyTableCellView: NSTableCellView { private var hostingView: NSHostingView<MyCellView>! init() { self.hostingView = NSHostingView(rootView: MyCellView(text: "", url: nil)) self.addSubview(self.hostingView) } func configureWith(text: String, url: URL) { let rootView = MyCellView(text: text, url: url) hostingView.rootView = rootView // How can I make this connection? self.textField = rootView.??? self.imageView = rootView.??? } } I'm ideally looking for a solution that works on macOS 15+.
2
0
84
3w