To whom it may concern that deals with bugs in SwiftUI for iOS 26:
Inadvertently discovered a bug which duplicates ToolbarItem in any placement in the toolbar when navigationBarBackButtonHidden is set to true.
.toolbar{
ToolbarItem(placement: .confirmationAction) {
Button("Stop", systemImage: "stop.fill"){
//some action
}
}
}
.navigationBarBackButtonHidden(true)
Expected Behavior
Show the ToolbarItem
Actual Behavior
Duplicates items in the placement position.
Thank you.
SwiftUI
RSS for tagProvide views, controls, and layout structures for declaring your app's user interface using SwiftUI.
Posts under SwiftUI tag
200 Posts
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
[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)
}
}
The zoom navigation transition with matchedTransitionSource in tabViewBottomAccessory does not work when a Published var in an ObservableObjector Observable gets changed.
Here is an minimal reproducible example with ObservableObject:
import SwiftUI
import Combine
private final class ViewModel: ObservableObject {
@Published var isPresented = false
}
struct ContentView: View {
@Namespace private var namespace
@StateObject private var viewModel = ViewModel()
// @State private var isPresented = false
var body: some View {
TabView {
Button {
viewModel.isPresented = true
} label: {
Text("Start")
}
.tabItem {
Image(systemName: "house")
Text("Home")
}
Text("Search")
.tabItem {
Image(systemName: "magnifyingglass")
Text("Search")
}
Text("Profile")
.tabItem {
Image(systemName: "person")
Text("Profile")
}
}
.sheet(isPresented: $viewModel.isPresented) {
Text("Sheet")
.presentationDragIndicator(.visible)
.navigationTransition(.zoom(sourceID: "tabViewBottomAccessoryTransition", in: namespace))
}
.tabViewBottomAccessory {
Button {
viewModel.isPresented = true
} label: {
Text("BottomAccessory")
}
.matchedTransitionSource(id: "tabViewBottomAccessoryTransition", in: namespace)
}
}
}
However, when using only a State property everything works:
import SwiftUI
import Combine
private final class ViewModel: ObservableObject {
@Published var isPresented = false
}
struct ContentView: View {
@Namespace private var namespace
// @StateObject private var viewModel = ViewModel()
@State private var isPresented = false
var body: some View {
TabView {
Button {
isPresented = true
} label: {
Text("Start")
}
.tabItem {
Image(systemName: "house")
Text("Home")
}
Text("Search")
.tabItem {
Image(systemName: "magnifyingglass")
Text("Search")
}
Text("Profile")
.tabItem {
Image(systemName: "person")
Text("Profile")
}
}
.sheet(isPresented: $isPresented) {
Text("Sheet")
.presentationDragIndicator(.visible)
.navigationTransition(.zoom(sourceID: "tabViewBottomAccessoryTransition", in: namespace))
}
.tabViewBottomAccessory {
Button {
isPresented = true
} label: {
Text("BottomAccessory")
}
.matchedTransitionSource(id: "tabViewBottomAccessoryTransition", in: namespace)
}
}
}
Let me ask the general question first, then explain the context...
Each Tab of a TabView defines a separate View hierarchy. (I'm assuming that the root view of each Tab defines its own NavigationStack.) Since an @Environment is supposed to serve data to the child views in its view hierarchy, does this mean that it is possible to define Environments in each tab's root view with the same name (i.e. key) but different values? (I.e., I want a subview to access an environment value for the current view hierarchy without requiring that the subview have any knowledge of which hierarchy it is being called from.)
The actual use case has to do with using @Environment in a tabbed application to inject a router in subviews. (Each Tab has its own NavigationStack and its own NavigationPath.)
I have an @Observable router class which manages a NavigationPath.. The root view of each Tab in the application has its own instance of that router object (and hence, it's own NavigationPath). I want to inject that router into all of the subviews in each Tab's view hierarchy, so that I can use path-based navigation.
My current implementation injects the router throughout the view hierarchies via constructor injection. This works, but is a real pain and includes a bunch of duplicate code. I would like to use @Environment injection instead, but this can only work if @Environment stores its EnvironmentValues on a per view-hierarchy (rather than a per-application) basis.
So,
can this approach work?
what experience can you share concerting router-based navigation in a TabView-based app?
Thanks.
Anytime I launch a view that contains a textfield, as soon as it’s in focus the view dismisses, and I log this warning, I have tried everything I could think of and still no solution, anyone know a workaround to this?
note: this happens both on simulator and physical devices
-[rtiinputsystemclient remotetextinputsessionwithid:performinputoperation:] perform input operation requires a valid sessionid. input modality = keyboard, input operation = , custom infotype = uiemojisearchoperations
The following code segments run when building and running the app, or after going home and re-opening the app, but now when quitting the app and re-opening it again. What code can do that?
init() {
print("test")
}
.onAppear {
print("test)
}
.onChange(of: scenePhase) { _, newValue in
print(newValue)
}
I am beginner to spacial computing and would like to build an enterprise solution for my enterprise on VisionOS. How can I accomplish that?
Topic:
Spatial Computing
SubTopic:
General
Tags:
Enterprise
SwiftUI
Business and Enterprise
visionOS
We have an UIViewController called InfoPlayerViewController. Its main subview is from a child view controller backed by SwiftUI via UIHostingController. The InfoPlayerViewController conforms to UIViewControllerTransitioningDelegate. The animation controller for dismissing is DismissPlayerAnimationController. It runs UIKit keyframe animations via UIViewPropertyAnimator. When the keyframe animation is executed there’s an occasional crash for end users in production. It only happens on iOS 26.
FB Radar: FB20871547
An example crash is below.
Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Reason: +[_SwiftUILayerDelegate _screen]: unrecognized selector sent to class 0x20c95da08
Termination Reason: SIGNAL 6 Abort trap: 6
Triggered by Thread: 0
Last Exception Backtrace:
0 CoreFoundation 0x1a23828c8 __exceptionPreprocess + 164 (NSException.m:249)
1 libobjc.A.dylib 0x19f2f97c4 objc_exception_throw + 88 (objc-exception.mm:356)
2 CoreFoundation 0x1a241e6cc +[NSObject(NSObject) doesNotRecognizeSelector:] + 364 (NSObject.m:158)
3 CoreFoundation 0x1a22ff4f8 ___forwarding___ + 1472 (NSForwarding.m:3616)
4 CoreFoundation 0x1a23073a0 _CF_forwarding_prep_0 + 96 (:-1)
5 UIKitCore 0x1a948e880 __35-[UIViewKeyframeAnimationState pop]_block_invoke + 300 (UIView.m:2973)
6 CoreFoundation 0x1a22cb170 __NSDICTIONARY_IS_CALLING_OUT_TO_A_BLOCK__ + 24 (NSDictionaryHelpers.m:10)
7 CoreFoundation 0x1a245d7cc -[__NSDictionaryM enumerateKeysAndObjectsWithOptions:usingBlock:] + 288 (NSDictionaryM.m:271)
8 UIKitCore 0x1a948e6bc -[UIViewKeyframeAnimationState pop] + 376 (UIView.m:2955)
9 UIKitCore 0x1a7bc40e8 +[UIViewAnimationState popAnimationState] + 60 (UIView.m:1250)
10 UIKitCore 0x1a94acc44 +[UIView(UIViewAnimationWithBlocks) _setupAnimationWithDuration:delay:view:options:factory:animations:start:animationStateGenerator:completion:] + 684 (UIView.m:17669)
11 UIKitCore 0x1a94ae334 +[UIView(UIViewKeyframeAnimations) animateKeyframesWithDuration:delay:options:animations:completion:] + 224 (UIView.m:17945)
12 MyApp 0x102c78dec static UIView.animateNestedKeyframe(withRelativeStartTime:relativeDuration:animations:) + 208 (UIView+AnimateNestedKeyframe.swift:10)
13 MyApp 0x102aef3c0 closure #1 in DismissPlayerAnimationController.slideDownBelowTabBarTransitionAnimator(using:) + 156 (DismissPlayerAnimationController.swift:229)
14 MyApp 0x102a2d3d4 <deduplicated_symbol> + 28
15 UIKitCore 0x1a7d5ae5c -[UIViewPropertyAnimator _runAnimations] + 172 (UIViewPropertyAnimator.m:2123)
16 UIKitCore 0x1a83e1594 __49-[UIViewPropertyAnimator startAnimationAsPaused:]_block_invoke_3 + 92 (UIViewPropertyAnimator.m:3557)
17 UIKitCore 0x1a83e1464 __49-[UIViewPropertyAnimator startAnimationAsPaused:]_block_invoke + 96 (UIViewPropertyAnimator.m:3547)
18 UIKitCore 0x1a83e1518 __49-[UIViewPropertyAnimator startAnimationAsPaused:]_block_invoke_2 + 144 (UIViewPropertyAnimator.m:3553)
19 UIKitCore 0x1a83e0e64 -[UIViewPropertyAnimator _setupAnimationTracking:] + 100 (UIViewPropertyAnimator.m:3510)
20 UIKitCore 0x1a83e1264 -[UIViewPropertyAnimator startAnimationAsPaused:] + 728 (UIViewPropertyAnimator.m:3610)
21 UIKitCore 0x1a83de42c -[UIViewPropertyAnimator pauseAnimation] + 68 (UIViewPropertyAnimator.m:2753)
22 UIKitCore 0x1a87d5328 -[UIPercentDrivenInteractiveTransition _startInterruptibleTransition:] + 244 (UIViewControllerTransitioning.m:982)
23 UIKitCore 0x1a87d5514 -[UIPercentDrivenInteractiveTransition startInteractiveTransition:] + 184 (UIViewControllerTransitioning.m:1012)
24 UIKitCore 0x1a7c7931c ___UIViewControllerTransitioningRunCustomTransitionWithRequest_block_invoke_3 + 152 (UIViewControllerTransitioning.m:1579)
25 UIKitCore 0x1a892aefc +[UIKeyboardSceneDelegate _pinInputViewsForKeyboardSceneDelegate:onBehalfOfResponder:duringBlock:] + 96 (UIKeyboardSceneDelegate.m:3518)
26 UIKitCore 0x1a7c79238 ___UIViewControllerTransitioningRunCustomTransitionWithRequest_block_invoke_2 + 236 (UIViewControllerTransitioning.m:1571)
27 UIKitCore 0x1a94ab4b8 +[UIView(Animation) _setAlongsideAnimations:toRunByEndOfBlock:animated:] + 188 (UIView.m:17089)
28 UIKitCore 0x1a7c79070 _UIViewControllerTransitioningRunCustomTransitionWithRequest + 556 (UIViewControllerTransitioning.m:1560)
29 UIKitCore 0x1a86cb7cc __77-[UIPresentationController runTransitionForCurrentStateAnimated:handoffData:]_block_invoke_3 + 1784 (UIPresentationController.m:1504)
30 UIKitCore 0x1a7c43888 -[_UIAfterCACommitBlock run] + 72 (_UIAfterCACommitQueue.m:137)
31 UIKitCore 0x1a7c437c0 -[_UIAfterCACommitQueue flush] + 168 (_UIAfterCACommitQueue.m:228)
32 UIKitCore 0x1a7c436d0 _runAfterCACommitDeferredBlocks + 260 (UIApplication.m:3297)
33 UIKitCore 0x1a7c43c34 _cleanUpAfterCAFlushAndRunDeferredBlocks + 80 (UIApplication.m:3275)
34 UIKitCore 0x1a7c1f104 _UIApplicationFlushCATransaction + 72 (UIApplication.m:3338)
35 UIKitCore 0x1a7c1f024 __setupUpdateSequence_block_invoke_2 + 352 (_UIUpdateScheduler.m:1634)
36 UIKitCore 0x1a7c2cee8 _UIUpdateSequenceRunNext + 128 (_UIUpdateSequence.mm:189)
37 UIKitCore 0x1a7c2c378 schedulerStepScheduledMainSectionContinue + 60 (_UIUpdateScheduler.m:1185)
38 UpdateCycle 0x28c58f5f8 UC::DriverCore::continueProcessing() + 84 (UCDriver.cc:288)
39 CoreFoundation 0x1a2323230 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 28 (CFRunLoop.c:2021)
40 CoreFoundation 0x1a23231a4 __CFRunLoopDoSource0 + 172 (CFRunLoop.c:2065)
41 CoreFoundation 0x1a2300c6c __CFRunLoopDoSources0 + 232 (CFRunLoop.c:2102)
42 CoreFoundation 0x1a22d68b0 __CFRunLoopRun + 820 (CFRunLoop.c:2983)
43 CoreFoundation 0x1a22d5c44 _CFRunLoopRunSpecificWithOptions + 532 (CFRunLoop.c:3462)
44 GraphicsServices 0x2416a2498 GSEventRunModal + 120 (GSEvent.c:2049)
45 UIKitCore 0x1a7c50ddc -[UIApplication _run] + 792 (UIApplication.m:3899)
46 UIKitCore 0x1a7bf5b0c UIApplicationMain + 336 (UIApplication.m:5574)
// ...
Hello,
Is it possible to integrate a database into Swift Playground on iPad? Otherwise, what can be done?
Thank you.
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
}
}
}
SwiftUI's colorScheme modifier is said to be deprecated in favour of preferredColorScheme but the two work differently. See the below sample app, colorScheme changes the underlying view colour while preferredColorScheme doesn't. Is that a bug of preferredColorScheme?
import SwiftUI
struct ContentView: View {
let color = Color(light: .red, dark: .green)
var body: some View {
VStack {
HStack {
color.colorScheme(.light)
color.colorScheme(.dark)
}
HStack {
color.preferredColorScheme(.light)
color.preferredColorScheme(.dark)
}
}
}
}
#Preview {
ContentView()
}
@main struct TheApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
extension UIColor {
convenience init(light: UIColor, dark: UIColor) {
self.init { v in
switch v.userInterfaceStyle {
case .light: light
case .dark: dark
case .unspecified: fatalError()
@unknown default: fatalError()
}
}
}
}
extension Color {
init(light: Color, dark: Color) {
self.init(UIColor(light: UIColor(light), dark: UIColor(dark)))
}
}
Hey there,
Link to the sample project: https://github.com/dev-loic/AppleSampleScrolling
Context
We are working on creating a feed of posts in SwiftUI. So far, we have successfully implemented a classic feed that opens from the top, with bottom pagination — a standard use case.
Our goal, however, is to allow the feed to open from any post, not just the first one.
For example, we would like to open the feed directly at the 3rd post and then trigger a network call to load elements both above and below it.
Our main focus here is on preserving the scroll position while opening the screen and waiting for the network call to complete.
To illustrate the issue, I created a sample project (attached) with two screens:
MainView, which contains buttons to open the feed in different states.
ScrollingView, which initially shows a single element, simulates a 3-second network call, and then populates with new data depending on which button was tapped.
I am currently using Xcode 26 beta 6, but I can also reproduce this issue on Xcode 16.3.
Tests on sample project
I click on a button and just wait the 3 seconds for the call.
In this scenario, I expect that the “focused item” stays at the exact same place on the screen. I also expect to see items below and above being added.
Simulator iPhone 16 / iOS 18.4 with itemsHeight = 100
position = 0, 1, 2, 3 ⇒ works as expected
position = 4, 5, 6, 7, 8, 9 ⇒ scroll is reset to the top and we loose the focused item
Simulator iPhone 16 / iOS 18.4 with itemsHeight = 500
position = 0, 1, 2, 3, 4 ⇒ works as expected
position = 5, 6, 7 ⇒ I have a glitch (the focused element moves on the screen) but the focused element is still visible
position = 8, 9 ⇒ scroll is reset to the top and we loose the focused item
Simulator iPhone 16 / iOS 26 with itemsHeight = 100 or 500
position = 0, 1, 2, 3, 4 ⇒ works as expected
position = 5, 6, 7, 8, 9 ⇒ I have a glitch (the focused element moves on the screen) but the focused element is still visible
Device iPhone 15 / iOS 26 with itemsHeight = 100
position = 0, 1, 2, 3, 4 ⇒ works as expected
position = 5, 6, 7, 8, 9 ⇒ I have a glitch (the focused element moves on the screen) but the focused element is still visible
Device iPhone 15 / iOS 26 with itemsHeight = 500
position = 0, 1, 2, 3 ⇒ works as expected
position = 4, 5, 6, 7, 8, 9 ⇒ I have a glitch (the focused element moves on the screen) but the focused element is still visible
Not any user interaction
Moreover, in this scenario, the user does not interact with the screen during the simulated network call. Regardless of the situation, if the ScrollView is in motion, its position always resets to the top. This behavior prevents us from implementing automatic pagination when scrolling upward, which is ultimately our goal.
My conclusion so far
As far as I know it seems not possible to have both keeping scroll possible and upward automatic pagination using a SwiftUI LazyVStack inside a ScrollView.
This appears to be standard behavior in messaging apps or other feed-based apps, and I’m wondering if I might be missing something.
Thank you in advance for any guidance you can provide on this topic.
Cheers
iOS 26 Beta 3 finally introduced an API for the clear variant of Liquid Glass. But is there any way to switch system controls like the NavigationController back button or UIBarButtonItems to clear? They do not accept an effect like UIEffectView, and they do not have a configuration property like UIButton.
Hi everyone,
I believe this should be a simple and expected default behavior in a real-world app, but I’m unable to make it work:
I have a View (a screen/page in this case) that calls an endpoint using async/await.
If the endpoint hasn’t finished, but I navigate forward to a DetailView, I want the endpoint to continue fetching data (i.e., inside the @StateObject ViewModel that the View owns). This way, when I go back, the View will have refreshed with the fetched data once it completes.
If the endpoint hasn’t finished and I navigate back to the previous screen, I want it to be canceled, and the @StateObject ViewModel should be deinitialized.
I can achieve 1 and 3 using the .task modifier, since it automatically cancels the asynchronous task when the view disappears:
view
.task { await vm.getData() }
I can achieve 1 and 2 using a structured Task in the View (or in the ViewModel, its the same behavior), for example:
.onFirstAppearOnly {
Task { away vm.getData() }
}
onFirstAppearOnly is a custom modifier that I have for calling onAppear only once in view lifecycle. Just to clarify, I dont think that part is important for the purpose of the example
My question is:
How can I achieve all three behaviors?
My minimum deployment target is iOS 15, and I’m using NavigationView + NavigationLink. However, I have also tried using NavigationStack + NavigationPath and still couldn’t get it to work.
Any help would be much appreciated. Thank you!
I'm working on a NavigationStack based app. Somewhere I'm using:
@Environment(\.dismiss) private var dismiss
and when trying to navigate to that view it gets stuck.
I used Self._printChanges() and discovered the environment variable dismiss is changing repeatedly. Obviously I am not changing that variable explicitly. I wasn't able to reproduce this in a small project so far, but does anybody have any idea what kind of thing I could be doing that might be causing this issue?
iOS 17.0.3
Hello Apple Developer Forum Community,
I’ve got a problem with the display of my SwiftUI View, that is tested on my physical iPhone. It’s shown very small (Picture) and on the Xcode Canvas Simulator it get’s shown right.
What is the problem with my code?
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!
I have a SwiftUI-based universal app which creates a file that it stores in documentsDirectory. On iOS/iPadOS, this file is stored in the application's Documents directory and is accessible via the Files app.
On MacCatalyst, this operation does the same thing — it creates the file and stores it in ~/Library/Containers/<app directory>/Data/Documents. However what I want is for the document to be stored in ~/Documents, so that it is easily accessible to the user.
How can I do that? I'd like it to occur without (for example) having to show a SaveFile panel...
I’m trying to understand how SwiftUI List handles row lifecycle and reuse during scrolling. I have a list with around 60 card views; on initial load, only about 7 rows are created, but after scrolling to the bottom all rows appear to be created, and when scrolling back to the top I again observe multiple updates and apparent re-creation of rows. I confirmed this behavior using Instruments by profiling my app. Even though each row has a stable identifier, the row views still seem to be destroyed and recreated, which doesn’t resemble UIKit’s cell reuse model. I’d like clarity on how List uses identifiers internally, what actually gets reused versus recreated, and how developers should reason about performance and view lifetime in this case.
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?