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

Posts under SwiftUI tag

200 Posts

Post

Replies

Boosts

Views

Activity

hapticpatternlibrary.plist error with Text entry fields in Simulator only
When I have a TextField or TextEditor, tapping into it produces these two console entries about 18 times each: CHHapticPattern.mm:487 +[CHHapticPattern patternForKey:error:]: Failed to read pattern library data: Error Domain=NSCocoaErrorDomain Code=260 "The file “hapticpatternlibrary.plist” couldn’t be opened because there is no such file." UserInfo={NSFilePath=/Library/Audio/Tunings/Generic/Haptics/Library/hapticpatternlibrary.plist, NSURL=file:///Library/Audio/Tunings/Generic/Haptics/Library/hapticpatternlibrary.plist, NSUnderlyingError=0x600000ca1b30 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}} <_UIKBFeedbackGenerator: 0x600003505290>: Error creating CHHapticPattern: Error Domain=NSCocoaErrorDomain Code=260 "The file “hapticpatternlibrary.plist” couldn’t be opened because there is no such file." UserInfo={NSFilePath=/Library/Audio/Tunings/Generic/Haptics/Library/hapticpatternlibrary.plist, NSURL=file:///Library/Audio/Tunings/Generic/Haptics/Library/hapticpatternlibrary.plist, NSUnderlyingError=0x600000ca1b30 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}} My app does not use haptics. This doesn't appear to cause any issues, although entering text can feel a bit sluggish (even on device), but I am unable to determine relatedness. None-the-less, it definitely is a lot of log noise. Code to reproduce in simulator (xcode 26.2; ios 26 or 18, with iPhone 16 Pro or iPhone 17 Pro): import SwiftUI struct ContentView: View { @State private var textEntered: String = "" @State private var textEntered2: String = "" @State private var textEntered3: String = "" var body: some View { VStack { Spacer() TextField("Tap Here", text: $textEntered) TextField("Tap Here Too", text: $textEntered2) TextEditor(text: $textEntered3) .overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(.primary, lineWidth: 1)) .frame(height: 100) Spacer() } } } #Preview { ContentView() } Tapping back and forth in these fields generates the errors each time. Thanks, Steve
1
0
75
12h
Performance in Large Datasets (SwiftUI+SwiftData app)
Hi everyone, In the simple app below, I have a QueryView that has LazyVStack containing 100k TextField's that edit the item's content. The items are fetched with a @Query. On launch, the app will generate 100k items. Once created, when I press any of the TextField's , a severe hang happens, and every time I type a single character, it will cause another hang over and over again. I looked at it in Instruments and it shows that the main thread is busy during the duration of the hang (2.31 seconds) updating QueryView. From the cause and effect graph, the update is caused by @Observable QueryController <Item>.(Bool). Why does it take too long to recalculate the view, given that it's in a LazyVStack? (In other words, why is the hang duration directly proportional to the number of items?) How to fix the performance of this app? I thought adding LazyVStack was all I need to handle the large dataset, but maybe I need to add a custom pagination with .fetchLimit on top of that? (I understand that ModelActor would be an alternative to @Query because it will make the database operations happen outside of the main thread which will fix this problem, but with that I will lose the automatic fetching of @Query.) Thank you for the help! import SwiftData import SwiftUI @main struct QueryPerformanceApp: App { var body: some Scene { WindowGroup { ContentView() .modelContainer(for: [Item.self], inMemory: true) } } } @Model final class Item { var name: String init(name: String) { self.name = name } } struct ItemDetail: View { @Bindable var item: Item var body: some View { TextField("Name", text: $item.name) } } struct QueryView: View { @Query private var items: [Item] var body: some View { ScrollView { LazyVStack { ForEach(items) { item in VStack { ItemDetail(item: item) } } } } } } struct ContentView: View { let itemCount = 100_000 @Environment(\.modelContext) private var context @State private var isLoading = true var body: some View { Group { if isLoading { VStack(spacing: 16) { ProgressView() Text("Generating \(itemCount) items...") } } else { QueryView() } } .task { for i in 1...itemCount { context.insert(Item(name: "Item \(i)")) } try? context.save() isLoading = false } } }
1
0
80
13h
`ImageRenderer.render` halts program with `EXC_BREAKPOINT` inside SwiftUI/AttributeGraph
This extension View { public func renderSomething() async throws { let renderer = ImageRenderer(content: self) // renderer.colorMode = .linear renderer.render { size, context in print(size) // ... } // ... } } let view: some View = ... view.renderSomething() // → exception will cause the program to exit with EXC_BREAKPOINT deep inside SwiftUI. This worked with previous versions of Xcode, SwiftUI, and macOS. Xcode Version 26.2 (17C52), macOS Sequoia 15.7.3, using toolchain bundled with Xcode.
0
0
9
15h
Bug: Xcode 26.2 wants `ENABLE_DEBUG_DYLIB`: How do I enable that in `Package.swift`?
Xcode tells me Previewing in executable targets now requires a new build layout for unoptimized builds. Either set ENABLE_DEBUG_DYLIB to YES for this target, or break out your preview code into a separate framework with its own scheme. How do enable that in Package.swift. swiftSettings don't work (.define and unsafeFlags with -D ...). Creating a library product that the executable then depends on doesn't help either. I have two targets, one is an executable target. The #Preview macro is in the non-executable target.
1
0
13
15h
Slow rendering List backed by SwiftData @Query
Hello, I've a question about performance when trying to render lots of items coming from SwiftData via a @Query on a SwiftUI List. Here's my setup: // Item.swift: @Model final class Item: Identifiable { var timestamp: Date var isOptionA: Bool init() { self.timestamp = Date() self.isOptionA = Bool.random() } } // Menu.swift enum Menu: String, CaseIterable, Hashable, Identifiable { var id: String { rawValue } case optionA case optionB case all var predicate: Predicate<Item> { switch self { case .optionA: return #Predicate { $0.isOptionA } case .optionB: return #Predicate { !$0.isOptionA } case .all: return #Predicate { _ in true } } } } // SlowData.swift @main struct SlowDataApp: App { var sharedModelContainer: ModelContainer = { let schema = Schema([Item.self]) let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false) return try! ModelContainer(for: schema, configurations: [modelConfiguration]) }() var body: some Scene { WindowGroup { ContentView() } .modelContainer(sharedModelContainer) } } // ContentView.swift struct ContentView: View { @Environment(\.modelContext) private var modelContext @State var selection: Menu? = .optionA var body: some View { NavigationSplitView { List(Menu.allCases, selection: $selection) { menu in Text(menu.rawValue).tag(menu) } } detail: { DemoListView(selectedMenu: $selection) }.onAppear { // Do this just once // (0..<15_000).forEach { index in // let item = Item() // modelContext.insert(item) // } } } } // DemoListView.swift struct DemoListView: View { @Binding var selectedMenu: Menu? @Query private var items: [Item] init(selectedMenu: Binding<Menu?>) { self._selectedMenu = selectedMenu self._items = Query(filter: selectedMenu.wrappedValue?.predicate, sort: \.timestamp) } var body: some View { // Option 1: touching `items` = slow! List(items) { item in Text(item.timestamp.description) } // Option 2: Not touching `items` = fast! // List { // Text("Not accessing `items` here") // } .navigationTitle(selectedMenu?.rawValue ?? "N/A") } } When I use Option 1 on DemoListView, there's a noticeable delay on the navigation. If I use Option 2, there's none. This happens both on Debug builds and Release builds, just FYI because on Xcode 16 Debug builds seem to be slower than expected: https://indieweb.social/@curtclifton/113273571392595819 I've profiled it and the SwiftData fetches seem blazing fast, the Hang occurs when accessing the items property from the List. Is there anything I'm overlooking or it's just as fast as it can be right now?
9
4
1.5k
18h
SwiftUI Instruments Template doesn't work
I am profiling a simple SwiftUI test app on my new iPhone through my new MacBook Pro and everything is version 26.2 (iOS, macOS, Xcode). I run Instruments with the SwiftUI template using all of the default settings and get absolutely zero data after interacting with the app for about 20 seconds. Using the Time Profiler template yields trace data. Trying the SwiftUI template again with the sample Landmarks app has the same issue as my app.
1
0
32
18h
macOS SwiftUI Sheets are no longer resizable (Xcode 16 beta2)
For whatever reason SwiftUI sheets don't seem to be resizable anymore. The exact same code/project produces resizable Sheets in XCode 15.4 but unresizable ones with Swift included in Xcode 16 beta 2. Tried explicitly providing .fixedSize(horizontal false, vertical: false) everywhere humanly possible hoping for a fix but sheets are still stuck at an awkward size (turns out be the minWidth/minHeight if I provide in .frame).
7
1
2.6k
19h
SwiftUI iOS 26 .safeAreaBar issue with large navigation title
I have some really straight forward code in a sample project. For some reason when the app launches the title is blurred obscured by scrolledgeeffect blur. If I scroll down the title goes small as it should do and all looks fine. If I scroll back to the top, just before it reaches the top the title goes large and it looks correct, but once it actually reaches/snaps to the top, is then incorrectly blurs again. Is there anything obvious I'm doing wrong? Is this a bug? struct ContentView: View { var body: some View { NavigationStack { ScrollView { VStack { Rectangle().fill(Color.red.opacity(0.2)).frame(height: 200) Rectangle().frame(height: 200) Rectangle().frame(height: 200) Rectangle().frame(height: 200) Rectangle().frame(height: 200) } } .safeAreaBar(edge: .top) { Text("Test") } .navigationTitle(Title") } } }
2
0
93
1d
fileImporter issue in visionOS with iPhone app (that can run on visionOS)
Happy new year to all! I have created an iOS app that also runs on Apple Vision Pro. On iOS, when you activate the fileImporter modal, you can swipe down the modal in iOS to dismiss. However, in visionOS, this same modal CANNOT be swiped down to cancel/dismiss. If you are drilled deep into a file hierarchy, you have to navigate back to the top level to tap X to dismiss. Is there a way to add swipe down to the visionOS implementation of fileImporter, or any other workaround so the user doesn't have to navigate back to the top to dismiss? Again, this is not a visionOS app but an iOS app compatible for use in Vision Pro. Thanks!
2
0
761
1d
NavigationStack back button ignores tint when presented in sheet
[Also submitted as FB21536505] When presenting a NavigationStack inside a .sheet, applying .tint(Color) does not affect the system back button on pushed destinations. The sheet’s close button adopts the tint, but the back chevron remains the default system color. REPRO Create a new iOS project and replace ContentView.swift with the code below. —or— Present a .sheet containing a NavigationStack. Apply .tint(.red) to the NavigationStack or sheet content. Push a destination using NavigationLink. EXPECTED The back button chevron adopts the provided tint color, consistent with other toolbar buttons and UIKit navigation behavior. ACTUAL The back button chevron remains the default system color. NOTES Reproduces consistently on: iOS 26.2 (23C54) iOS 26.3 (23D5089e) SCREEN RECORDING SAMPLE CODE import SwiftUI struct ContentView: View { @State private var isSheetPresented = false var body: some View { Button("Open Settings Sheet") { isSheetPresented = true } .sheet(isPresented: $isSheetPresented) { NavigationStack { List { NavigationLink("Push Detail") { DetailView() } } .navigationTitle("Settings") .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .automatic) { Button("Close", systemImage: "xmark") { isSheetPresented = false } } } } .tint(.red) } } } private struct DetailView: View { var body: some View { List { Text("Detail View") } .navigationTitle("Detail") .navigationBarTitleDisplayMode(.inline) } }
3
1
92
1d
Camera Permissions Popup
We have a very strange issue that I am trying to solve or find the best practice for. We have a SwiftUI View that uses the Camera to preview. So as suggested in Apples Docs we check authorisation status and then if it's not determined we request authorisation. We also have the privacy entry in the info.plist case .notDetermined: AVCaptureDevice.requestAccess(for: .video) { accessStatusAuthorised in if !accessStatusAuthorised { self.cameraStatus = .notAuthorised } else { self.isAuthorized = true self.cameraStatus = .authorised self.startCameraSession(cameraPosition: cameraPosition) } } case .restricted: cameraStatus = .notAuthorised isAuthorized = false case .denied: cameraStatus = .notAuthorised isAuthorized = false case .authorized: cameraStatus = .authorised isAuthorized = true startCameraSession(cameraPosition: cameraPosition) break @unknown default: isAuthorized = true cameraStatus = .notAuthorised } However when we call this code it freezes the Camera feed, even when allow has been tapped. However and this is the confusing part. If we do not call the code above, we still get the permission for camera access pop up and the camera works fine after allowing. What im concerned about is changing the code to do this and its a possible apple bug that gets fixed and hey then none of the Apps allow the camera function. I cannot see any where that the process has changed for iOS 26 / Xcode 26. Can anyone shed any light on this or had similar experience ?
1
0
34
1d
Choppy minimized search bar animation
The new .searchToolbarBehavior(.minimized) modifier leads to a choppy animation both on device and SwiftUI canvas (iOS 26.2): I assume this is not the intended behaviour (reported under FB21572657), but since I almost never receive any feedback to my reports, I wanted to see also here, whether you experience the same, or perhaps I use the modifier incorrectly? struct SwiftUIView: View { @State var isSearchPresented: Bool = false @State var searchQuery: String = "" var body: some View { TabView { Tab { NavigationStack { ScrollView { Text(isSearchPresented.description) } .navigationTitle("Test") } .searchable(text: $searchQuery, isPresented: $isSearchPresented) .searchToolbarBehavior(.minimize) // **Choppy animation comes from here?** } label: { Label("Test", systemImage: "calendar") } Tab { Text("123") } label: { Label("123", systemImage: "globe") } } } } #Preview { if #available(iOS 26, *) { SwiftUIView() } else { // Fallback on earlier versions } }
4
0
297
2d
visionOS pushWindow being dismissed on app foreground
We seen to have found an issue when using the pushWindow action on visionOS. The issue occurs if the app is backgrounded then reopened by selecting the apps icon on the home screen. Any window that is opened via the pushWindow action is then dismissed. We've been able to replicate the issue in a small sample project. Replication steps Open app Open window via the push action Press the digital crown On the home screen select the apps icon again The pushed window will now be dismissed. There is a sample project linked here that shows off the issue, including a video of the bug in progress
3
1
689
3d
[SwiftUI][DragDrop][iPadOS] Drop into TabView Sidebar Tab not triggering. How to debug?
Are there tools to inspect why a drag-and-drop drop is not triggering in a SwiftUI app? I've declared .draggable on the dragging view, and .dropDestination on the receiving TabContent Tab view. This combination of modifiers is working on a smaller demo app that I have, but not on my more complex one. Is there a means to debug this in SwiftUI? I'd like to see if the drag-and-drop pasteboard actually has what I think it should have on it. Notably: "TabContent" has a far more restricted list of modifiers that can be used on it.
0
0
68
3d
UI Tests troubles with Xcode 26.1 and Xcode 26.2
Since I moved to Xcode 26.1 and Xcode 26.2 then, my UI tests all fail only for iOS 26+, for both simulator and real device. Everything worked perfectly with Xcode 26.0, and the code base of the application under test and the test cases are the same. With Xcode 26.0, the tests pass for iOS 26+ and iOS < 26, for both simulator and real device. In addition, even the Accessibility Inspector tool fails to display the view hierarchy for iOS 26+ with Xcode 26.2. With Xcode 26.0, whatever are the devices and the OS versions, the tool was able to display the view hierarchy. Otherwise the tool is empty even if the device and app are selected. This failing tests issue occurs both on my local environment and on GitHub Actions runners, excluding the hypothesis I have troubles with my own side. The error message for failing tests explains the element cannot be found anymore. Given for example the test case: @MainActor func testMakeScreenshotsForDocumentation_Button() { let app = launchApp() goToComponentsSheet(app) waitForButtonToAppear(withWording: "app_components_button_label", app) tapButton(withWording: "app_components_button_label", app) tapButton(withWording: "Strong", app) takeScreenshot(named: "component_button_", ACDC.buttonX, ACDC.buttonY, ACDC.buttonWidth, ACDC.buttonHeight, app) } the goToComponentSheet(app) line shows the error: ActionsDocumentationScreenshots.testMakeScreenshotsForDocumentation_Button() In details the function: /// Opens the page of the components, i.e. tap on the 2nd of the tab bar @MainActor func goToComponentsSheet(_ app: XCUIApplication) { app.tabBars.buttons.element(boundBy: 1).tap() } with the following error on the app.tabBars line: .../AppTestCase.swift:157 testMakeScreenshotsForDocumentation_Button(): Failed to tap Button (Element at index 1): No matches found for Descendants matching type TabBar from input {(Application, pid: 1883)} I have the feeling with Xcode 26.2 (and Xcode 26.1) the view hierarchy is not accessible anymore for both XCUITest framework and Accessibility Inspector tool. Note I have on my side macOS Tahoe 26.1 (25B78) and my GitHub Actions runner are on macOS 26.0.1 (25A362). When I used Xcode 26.0 I was on macOS Tahoe 26.1 (25B78) . Any ideas? 🙂
2
0
128
3d
NSHostingView stops receiving mouse events when layered above another NSHostingView (macOS Tahoe 26.2)
I’m running into a problem with SwiftUI/AppKit event handling on macOS Tahoe 26.2. I have a layered view setup: Bottom: AppKit NSView (NSViewRepresentable) Middle: SwiftUI view in an NSHostingView with drag/tap gestures Top: Another SwiftUI view in an NSHostingView On macOS 26.2, the middle NSHostingView no longer receives mouse or drag events when the top NSHostingView is present. Events pass through to the AppKit view below. Removing the top layer immediately restores interaction. Everything works correctly on macOS Sequoia. I’ve posted a full reproducible example and detailed explanation on Stack Overflow, including a single-file demo: Stack Overflow post: https://stackoverflow.com/q/79862332 I also found a related older discussion here, but couldn’t get the suggested workaround to apply: https://developer.apple.com/forums/thread/759081 Any guidance would be appreciated. Thanks!
2
0
241
4d
Pickers in toolbar expand its width
With iOS 26 there has been a change in behavior with Pickers in the toolbar. The Picker looks expanded unlike other views such as a Button and Menu. See screenshots below. Is this the intended behavior or a bug? (I already submitted a feedback for this at FB19276474) What Picker looks like in the toolbar: What Button looks like in the toolbar:
1
0
89
4d
onWorldRecenter memory leak and duplicate callbacks in ImmersiveSpace
Posting this here in case this information is helpful to other developers: As of visionOS 26.3 beta 1, onWorldRecenter has two significant issues: (FB21557639) Memory Leak: When onWorldRecenter is assigned to a RealityView within an ImmersiveSpace, it appears to retain a strong reference to the view's internal SwiftUI context. When the immersive space is dismissed, the view's @State objects will not be deallocated. Also, each time the immersive space view's body is executed, additional state storage will be allocated and leaked. Multiple Callbacks: When the user long-presses the Digital Crown, the onWorldRecenter closure will be called multiple times, once for each past view body execution, including those of immersive space views that have been previously dismissed. Although these issues seem to be most prevalent when onWorldRecenter is used with an ImmersiveSpace, they may also occur in the context of a WindowGroup under certain circumstances. It's possible to work around this problem by moving onWorldRecenter to an empty overlay view within the app's primary WindowGroup and forwarding the world recenter events to ImmersiveSpace views through a notification system, coupled with a debouncer as an extra precaution.
0
0
516
4d
interactive glassEffect bug?
Applying glass effect, providing a shape isn't resulting in the provided shape rendering the interaction correctly. .glassEffect(.regular.tint(Color(event.calendar.cgColor)).interactive(), in: .rect(cornerRadius: 20)) results in properly drawn view but interactive part of it is off. light and shimmer appear as a capsule within the rect.
3
12
320
4d