I have a UIViewController that uses MKMapview to display the motion history trajectory. Repeatedly entering and exiting UIViewController will cause a crash, and the crash stack is as follows:
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_INVALID_ADDRESS at 0x000000014bfc0fc8
Exception Codes: 0x0000000000000001, 0x000000014bfc0fc8
VM Region Info: 0x14bfc0fc8 is not in any region. Bytes after previous region: 217033 Bytes before following region: 61496
REGION TYPE START - END [ VSIZE] PRT/MAX SHRMOD REGION DETAIL
VM_ALLOCATE 14bf88000-14bf8c000 [ 16K] rw-/rwx SM=PRV
---> GAP OF 0x44000 BYTES
VM_ALLOCATE 14bfd0000-14bfd4000 [ 16K] rw-/rwx SM=PRV
Termination Reason: SIGNAL 11 Segmentation fault: 11
Terminating Process: exc handler [1881]
Triggered by Thread: 8
Thread 8 name: Dispatch queue: com.apple.root.background-qos
Thread 8 Crashed:
0 CoreFoundation 0x19e36ac40 CFRelease + 44
1 VectorKit 0x1ce16af6c md::TileGroupNotificationManager::~TileGroupNotificationManager() + 132
2 VectorKit 0x1cd6f7178 <deduplicated_symbol> + 76
3 VectorKit 0x1cdba8d74 -[VKSharedResources .cxx_destruct] + 32
4 libobjc.A.dylib 0x19b3321f8 object_cxxDestructFromClass(objc_object*, objc_class*) + 116
5 libobjc.A.dylib 0x19b32df20 objc_destructInstance_nonnull_realized(objc_object*) + 76
6 libobjc.A.dylib 0x19b32d4a4 _objc_rootDealloc + 72
7 VectorKit 0x1cdba93fc -[VKSharedResources dealloc] + 476
8 VectorKit 0x1cdafa3fc -[VKSharedResourcesManager _removeResourceUser] + 68
9 VectorKit 0x1cdafa380 +[VKSharedResourcesManager removeResourceUser] + 44
10 VectorKit 0x1cdafa2fc __37-[VKIconManager _internalIconManager]_block_invoke + 168
11 libdispatch.dylib 0x1d645b7ec _dispatch_client_callout + 16
12 libdispatch.dylib 0x1d6446664 _dispatch_continuation_pop + 596
13 libdispatch.dylib 0x1d6459528 _dispatch_source_latch_and_call + 396
14 libdispatch.dylib 0x1d64581fc _dispatch_source_invoke + 844
15 libdispatch.dylib 0x1d6453f48 _dispatch_root_queue_drain + 364
16 libdispatch.dylib 0x1d64546fc _dispatch_worker_thread2 + 180
17 libsystem_pthread.dylib 0x1f9b7e37c _pthread_wqthread + 232
18 libsystem_pthread.dylib 0x1f9b7d8c0 start_wqthread + 8
I have checked the code and did not find any issues. I have also tested on iOS 15, 16, and 18 without any issues. Could this be an error in the iOS 26 system? Have you ever met any friends? I hope to receive an answer. Thank you.
Explore the various UI frameworks available for building app interfaces. Discuss the use cases for different frameworks, share best practices, and get help with specific framework-related questions.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
Hi there! I'm making an app that stores data for the user's profile in SwiftData. I was originally going to use UserDefaults but I thought SwiftData could save Images natively but this is not true so I really could switch back to UserDefaults and save images as Data but I'd like to try to get this to work first. So essentially I have textfields and I save the values of them through a class allProfileData. Here's the code for that:
import SwiftData
import SwiftUI
@Model
class allProfileData {
var profileImageData: Data?
var email: String
var bio: String
var username: String
var profileImage: Image {
if let data = profileImageData,
let uiImage = UIImage(data: data) {
return Image(uiImage: uiImage)
} else {
return Image("DefaultProfile")
}
}
init(email:String, profileImageData: Data?, bio: String, username:String) {
self.profileImageData = profileImageData
self.email = email
self.bio = bio
self.username = username
}
}
To save this I create a new class (I think, I'm new) and save it through ModelContext
import SwiftUI
import SwiftData
struct CreateAccountView: View {
@Query var profiledata: [allProfileData]
@Environment(\.modelContext) private var modelContext
let newData = allProfileData(email: "", profileImageData: nil, bio: "", username: "")
var body: some View {
Button("Button") {
newData.email = email
modelContext.insert(newData)
try? modelContext.save()
print(newData.email)
}
}
}
To fetch the data, I originally thought that @Query would fetch that data but I saw that it fetches it asynchronously so I attempted to manually fetch it, but they both fetched nothing
import SwiftData
import SwiftUI
@Query var profiledata: [allProfileData]
@Environment(\.modelContext) private var modelContext
let fetchRequest = FetchDescriptor<allProfileData>()
let fetchedData = try? modelContext.fetch(fetchRequest)
print("Fetched count: \(fetchedData?.count ?? 0)")
if let imageData = profiledata.first?.profileImageData,
let uiImage = UIImage(data: imageData) {
profileImage = Image(uiImage: uiImage)
} else {
profileImage = Image("DefaultProfile")
}
No errors. Thanks in advance
I have SwiftData models containing arrays of Codable structs that worked fine before adding CloudKit capability. I believe they are the reason I started seeing errors after enabling CloudKit.
Example model:
@Model
final class ProtocolMedication {
var times: [SchedulingTime] = [] // SchedulingTime is Codable
// other properties...
}
After enabling CloudKit, I get this error logged to the console:
'NSKeyedUnarchiveFromData' should not be used to for un-archiving and will be removed in a future release
CloudKit Console shows this times data as "plain text" instead of "bplist" format.
Other struct/enum properties display correctly (I think) as "bplist" in CloudKit Console.
The local SwiftData storage handled these arrays fine - this issue only appeared with CloudKit integration.
What's the recommended approach for storing arrays of Codable structs in SwiftData models that sync with CloudKit?
From what I understand, you’re meant to pass information like a view model to a content view through its configuration state. What about callbacks (e.g. something like didClickButton)? They aren’t “inputs” into the content configuration like a view model would be, but it feels odd to create and apply a content configuration only to specify callbacks and nothing else.
My app has the following UI layout:
NSSplitViewController as the windows contentViewController
NSPageController in the content (right) split item
NSTabViewController as the root items of the NSPageController
NSViewController with a collection view in the first tab of that NSTabViewController
The collection view is using a NSCollectionViewCompositionalLayout in which the sections are set up to have a header using NSCollectionLayoutBoundarySupplementaryItem with pinToVisibleBounds=true and alignment=top
With macOS 26, the pinned supplementary item automatically gets a blurred/semi-transparent background that seamlessly integrates with the toolbar. When the window's title bar has a NSTitlebarAccessoryViewController added, the said semi-transparent background gets a bottom hard edge and a hairline to provide more visual separation from the main content.
During runtime, my NSPageController transitions from the NSTabViewController to another view controller. When transitioning back, the semi-transparent blur bleeds into the entire section. This happens no matter if there's a NSTitlebarAccessoryViewController added or not.
It doesn't happen 100% of the cases, it seems to depend on section size, header visibility and/or scroll position. But it happens more often than not.
Most of the time, a second or so after the back transition - shortly after pageControllerDidEndLiveTransition: of the NSPageControllerDelegate is called - the view updates and the supplementary views are back to normal.
Sometimes, the issue also appears not when transitioning using NSPageController, but simply by scrolling through the collection view.
Anyone has an idea what is happening here? Below are two screenshots of both the "ok" and "not ok" state
I'm on macOS 26.0.1 and I'm using XCode 26.0.1
hello, I have been receiving crash reports on iPadOS 26.1, When UITrackingElementWindowController viewDidDisappear
The feedback associated with this post is: FB20986398 and Exception
Exception
'Cannot remove an observer <PKTextEffectsWindowObserver 0x10854cbe0> for the key path "frame" from <UITextEffectsWindow 0x10827ca00> because it is not registered as an observer.'
#1 0x0000000183529814 in objc_exception_throw ()
#2 0x00000001845065a4 in -[NSObject(NSKeyValueObserverRegistration) _removeObserver:forProperty:] ()
#3 0x00000001845069c8 in -[NSObject(NSKeyValueObserverRegistration) removeObserver:forKeyPath:] ()
#4 0x00000001845068e0 in -[NSObject(NSKeyValueObserverRegistration) removeObserver:forKeyPath:context:] ()
#5 0x00000001cb22e894 in -[PKTextEffectsWindowObserver dealloc] ()
#6 0x000000018beafb28 in _setInteractionView ()
#7 0x000000018d81e8b8 in -[UIView(Dragging) removeInteraction:] ()
#8 0x00000001cb216448 in -[PKTextInputInteraction willMoveToView:] ()
#9 0x000000018beafb1c in _setInteractionView ()
#10 0x000000018d81e8b8 in -[UIView(Dragging) removeInteraction:] ()
#11 0x000000018d5ab094 in -[UIEditingOverlayViewController _removeInteractions] ()
#12 0x000000018cb166a8 in -[UIViewController _setViewAppearState:isAnimating:] ()
#13 0x000000018cb16d70 in __52-[UIViewController _setViewAppearState:isAnimating:]_block_invoke_2 ()
#14 0x000000018cb16c10 in __52-[UIViewController _setViewAppearState:isAnimating:]_block_invoke ()
#15 0x000000018655ef78 in __NSARRAY_IS_CALLING_OUT_TO_A_BLOCK__ ()
#16 0x00000001866b4a24 in -[__NSArrayI enumerateObjectsWithOptions:usingBlock:] ()
#17 0x000000018cb16a44 in -[UIViewController _setViewAppearState:isAnimating:] ()
#18 0x000000018cb1753c in -[UIViewController __viewDidDisappear:] ()
#19 0x000000018cb17638 in -[UIViewController _endAppearanceTransition:] ()
#20 0x000000018ca2401c in __48-[UIPresentationController transitionDidFinish:]_block_invoke ()
#21 0x000000018ca23cd0 in -[UIPresentationController transitionDidFinish:] ()
#22 0x000000018ca2d720 in -[_UICurrentContextPresentationController transitionDidFinish:] ()
#23 0x000000018ca27608 in __77-[UIPresentationController runTransitionForCurrentStateAnimated:handoffData:]_block_invoke.106 ()
#24 0x000000018cb31fec in -[_UIViewControllerTransitionContext completeTransition:] ()
#25 0x000000018d7f09bc in -[UITransitionView notifyDidCompleteTransition:] ()
#26 0x000000018d7f0750 in -[UITransitionView _didCompleteTransition:] ()
#27 0x000000018bf1c2a4 in __UIVIEW_IS_EXECUTING_ANIMATION_COMPLETION_BLOCK__ ()
#28 0x000000018d817960 in -[UIViewAnimationBlockDelegate _didEndBlockAnimation:finished:context:] ()
#29 0x000000018d7f7168 in -[UIViewAnimationState sendDelegateAnimationDidStop:finished:] ()
#30 0x000000018d7f75cc in -[UIViewAnimationState animationDidStop:finished:] ()
#31 0x000000018d7f763c in -[UIViewAnimationState animationDidStop:finished:] ()
#32 0x0000000186fedda4 in run_animation_callbacks ()
#33 0x000000010365e2d0 in _dispatch_client_callout ()
#34 0x000000010367f4c0 in _dispatch_main_queue_drain.cold.5 ()
#35 0x0000000103654778 in _dispatch_main_queue_drain ()
#36 0x00000001036546b4 in _dispatch_main_queue_callback_4CF ()
#37 0x00000001865b42c8 in __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ ()
#38 0x0000000186567b3c in __CFRunLoopRun ()
#39 0x0000000186566a6c in _CFRunLoopRunSpecificWithOptions ()
#40 0x0000000226ee5498 in GSEventRunModal ()
#41 0x000000018bf2aba4 in -[UIApplication _run] ()
#42 0x000000018bed3a78 in UIApplicationMain ()
Let's say you have a NavigationModel that contains three NavigationPaths, one for each option in the sidebar for a NavigationSplitView.
This NavigationModel is created by the App and passed down to the root view for the scene in its environment.
Each option has a separate NavigationStack and is passed a binding to the appropriate NavigationPath from the NavigationModel.
Is it expected that when the user changes the selection in the sidebar, the NavigationPath for the newly selected view should be erased?
This is what's currently happening on macOS 26. It seems like the default action when creating a NavigationStack and passing it a binding to a NavigationPath is to clear that path and start from the root view.
Is this normal, intended behaviour or is it a bug? Or, perhaps, an option or modifier I am missing?
In one of my apps, i am using .glassEffect(_:In) to add glass effect on various elements. The app always crushes when a UI element with glassEffect(_in:) modifier is being rendered. This only happens on device running iOS 26 public beta. I know this for certain because I connected the particular device to xcode and run the app on the device. When i comment out the glassEffect modifier, app doesn't crush.
Is it possible to check particular realeases with #available? If not, how should something like this be handled. Also how do i handle such os level erros without the app crushing. Thanks.
Is anyone else getting new warning about menu items with submenus when running on Tahoe? I'm getting big performance problems using my menu as well as seeing these messages and I'm wondering if there's a connection.
My app is faceless with a NSStatusItem with an NSMenu. Specifically it's my own subclass of NSMenu where I have a lot of code to manage the menu's dynamic behavior. This code is directly in the menu subclass instead of in a controller because the app I forked had it this way, a little wacky but I don't see it being a problem. A nib defines the contents of the menu, and it's instantiated manually with code like:
var nibObjects: NSArray? = []
guard let nib = NSNib(nibNamed: "AppMenu", bundle: nil) else { ... }
guard nib.instantiate(withOwner: owner, topLevelObjects: &nibObjects) else { ... }
guard let menu = nibObjects?.compactMap({ $0 as? Self }).first else { ... }
Within that nib.instantiate call I see a warning logged that seems new to Tahoe, before the menu's awakeFromNib is called, that says (edited):
Internal inconsistency in menus - menu <NSMenu: 0x6000034e5340> believes it has <My_StatusItem_App.AppMenu: 0x7f9570c1a440> as a supermenu, but the supermenu does not seem to have any item with that submenu
My_StatusItem_App.AppMenu: 0x7f9570c1a440 is my menu belonging to the NSStatusItem, NSMenu: 0x6000034e5340 is the submenu of one of its menu items.
At a breakpoint in the NSMenu subclass's awakeFromNib I print self and see clear evidence of the warning's incorrectness. Below is a snippet of the console including the full warning, only edited for clarity and brevity. It shows on line 32 menu item with placeholder title "prototype batch item" that indeed has that submenu.
Internal inconsistency in menus - menu <NSMenu: 0x6000034e5340>
Title:
Supermenu: 0x7f9570c1a440 (My StatusItem App), autoenable: YES
Previous menu: 0x0 (None)
Next menu: 0x0 (None)
Items: (
"<NSMenuItem: 0x6000010e4fa0 Do The Thing Again, ke mask='<none>'>",
"<NSMenuItem: 0x6000010e5040 Customize\U2026, ke mask='<none>'>",
"<NSMenuItem: 0x6000010e50e0, ke mask='<none>'>"
) believes it has <My_StatusItem_App.AppMenu: 0x7f9570c1a440>
Title: My StatusItem App
Supermenu: 0x0 (None), autoenable: YES
Previous menu: 0x0 (None)
Next menu: 0x0 (None)
Items: (
) as a supermenu, but the supermenu does not seem to have any item with that submenu
(lldb) po self
<My_StatusItem_App.AppMenu: 0x7f9570c1a440>
Title: My StatusItem App
Supermenu: 0x0 (None), autoenable: YES
Previous menu: 0x0 (None)
Next menu: 0x0 (None)
Items: (
"<NSMenuItem: 0x6000010fd7c0 About My StatusItem App\U2026, ke mask='<none>', action: showAbout:, action image: info.circle>",
"<NSMenuItem: 0x6000010fd860 Show Onboarding Window\U2026, ke mask='Shift', action: showIntro:>",
"<NSMenuItem: 0x6000010fd900 Update Available\U2026, ke mask='<none>', action: installUpdate:, standard image: icloud.and.arrow.down, hidden>",
"<NSMenuItem: 0x6000010e46e0, ke mask='<none>'>",
"<NSMenuItem: 0x6000010e4780 Start The Thing, ke mask='<none>', action: startTheThing:>",
"<NSMenuItem: 0x6000010e4dc0 \U2318-\U232b key detector item, ke mask='<none>', view: <My_StatusItem_App.KeyDetectorView: 0x7f9570c1a010>>",
"<NSMenuItem: 0x6000010e4e60, ke mask='<none>'>",
"<NSMenuItem: 0x6000010e4f00 saved batches heading item, ke mask='<none>', view: <NSView: 0x7f9570b4be10>, hidden>",
"<My_StatusItem_App.BatchMenuItem: 0x6000016e02c0 prototype batch item, ke mask='<none>', action: replaySavedBatch:, submenu: 0x6000034e5340 ()>",
"<NSMenuItem: 0x6000010f7d40, ke mask='<none>'>",
"<My_StatusItem_App.ClipMenuItem: 0x7f956ef14fd0 prototype copy clip item, ke mask='<none>', action: copyClip:>",
"<NSMenuItem: 0x6000010fa620 Settings\U2026, ke='Command-,', action: showSettings:>",
"<NSMenuItem: 0x6000010fa6c0, ke mask='<none>'>",
"<NSMenuItem: 0x6000010fa760 Quit My StatusItem App, ke='Command-Q', action: quit:>"
)
Is this seemingly incorrect inconsistency message harmless? Am I only grasping at straws to think it has some connection to the performance issues with this menu?
Scenario: Typing Chinese Zhuyin “ㄨㄤ” and then selecting the candidate word “王”.
On iOS 18, the delegate (textField:shouldChangeCharactersInRange:replacementString:) is called with:
range: {0, 2}
replacementString: "王"
On iOS 26, the delegate (textField:shouldChangeCharactersInRanges:replacementString:) instead provides:
ranges: [{2, 0}]
replacementString: "王"
This results in inconsistent text input handling compared to earlier system versions.
Implement: Limit user input to a maximum of 100 Chinese characters.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if ([textField markedTextRange]) {
return YES;
}
NSString *changedString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if (changedString.length > 100) {
return NO;
}
return YES;
}
Questions:
Is this an intentional change in iOS 26?
If intentional, what is the recommended way to handle such cases in order to support both iOS 18 and iOS 26 consistently?
Sidebars for mac Catalyst apps running with UIDesignRequiresCompatibility flag render their active items with a white bg tint – resulting in labels and icons being not visible.
mac OS Tahoe 26.1 Beta 3 (25B5062e)
FB20765036
Example (Apple Developer App):
Crash in UIKeyboardStateManager when repeatedly switching text input focus in WKWebView (hybrid app)
We’re building a hybrid iOS app using Angular (web) rendered inside a WKWebView, hosted by a native Swift app.
Recently, we encountered a crash related to UIKeyboardStateManager in UIKit when switching between text inputs continuously within an Angular screen.
Scenario
The screen contains several text input fields.
A “Next” button focuses the next input field programmatically.
After about 61 continuous input field changes, the app crashes.
It seems like this may be related to UIKit’s internal keyboard management while switching focus rapidly inside a WebView.
crash stack:
Crashed: com.apple.main-thread
0 WebKit 0xfbdad0 <redacted> + 236
1 UIKitCore 0x10b0548 -[UITextInteractionSelectableInputDelegate _moveToStartOfLine:withHistory:] + 96
2 UIKitCore 0xd0fb38 -[UIKBInputDelegateManager _moveToStartOfLine:withHistory:] + 188
3 UIKitCore 0xa16174 __158-[_UIKeyboardStateManager handleMoveCursorToStartOfLine:beforePublicKeyCommands:testOnly:savedHistory:force:canHandleSelectableInputDelegateCommand:keyEvent:]_block_invoke + 52
4 UIKitCore 0xa36ae4 -[_UIKeyboardStateManager performBlockWithTextInputChangesIgnoredForNonMacOS:] + 48
5 UIKitCore 0xa160f0 -[_UIKeyboardStateManager handleMoveCursorToStartOfLine:beforePublicKeyCommands:testOnly:savedHistory:force:canHandleSelectableInputDelegateCommand:keyEvent:] + 440
6 UIKitCore 0xa07010 -[_UIKeyboardStateManager handleKeyCommand:repeatOkay:options:] + 5760
7 UIKitCore 0xa2fb64 -[_UIKeyboardStateManager _handleKeyCommandCommon:options:] + 76
8 UIKitCore 0xa2fb08 -[_UIKeyboardStateManager _handleKeyCommand:] + 20
9 UIKitCore 0xa30684 -[_UIKeyboardStateManager handleKeyEvent:executionContext:] + 2464
10 UIKitCore 0xa2f95c __42-[_UIKeyboardStateManager handleKeyEvent:]_block_invoke + 40
11 UIKitCore 0x4b9460 -[UIKeyboardTaskEntry execute:] + 208
12 UIKitCore 0x4b92f4 -[UIKeyboardTaskQueue continueExecutionOnMainThread] + 356
13 UIKitCore 0x4b8be0 -[UIKeyboardTaskQueue addTask:breadcrumb:] + 120
14 UIKitCore 0x4a9ed0 -[_UIKeyboardStateManager _setupDelegate:delegateSame:hardwareKeyboardStateChanged:endingInputSessionIdentifier:force:delayEndInputSession:] + 3388
15 UIKitCore 0xfa290 -[_UIKeyboardStateManager setDelegate:force:delayEndInputSession:] + 628
16 UIKitCore 0xf617c -[UIKeyboardSceneDelegate _reloadInputViewsForKeyWindowSceneResponder:force:fromBecomeFirstResponder:] + 1140
17 UIKitCore 0xf5c88 -[UIKeyboardSceneDelegate _reloadInputViewsForResponder:force:fromBecomeFirstResponder:] + 88
18 UIKitCore 0x4fe4ac -[UIResponder(UIResponderInputViewAdditions) reloadInputViews] + 84
19 WebKit 0xfbe708 <redacted> + 100
20 WebKit 0xfbf594 <redacted> + 340
21 WebKit 0x8a33d8 <redacted> + 32
22 WebKit 0x8cee04 <redacted> + 144
23 WebKit 0x1c83f0 <redacted> + 22692
24 WebKit 0x73f40 <redacted> + 264
25 WebKit 0x162c7c <redacted> + 40
26 WebKit 0x1623b4 <redacted> + 1608
27 WebKit 0x73298 <redacted> + 268
28 WebKit 0x72e48 <redacted> + 660
29 JavaScriptCore 0xdb00 WTF::RunLoop::performWork() + 524
30 JavaScriptCore 0xd744 WTF::RunLoop::performWork(void*) + 36
31 CoreFoundation 0xf92c __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 28
32 CoreFoundation 0xf744 __CFRunLoopDoSource0 + 172
33 CoreFoundation 0xf5a0 __CFRunLoopDoSources0 + 232
34 CoreFoundation 0xff20 __CFRunLoopRun + 840
35 CoreFoundation 0x11adc CFRunLoopRunSpecific + 572
36 GraphicsServices 0x1454 GSEventRunModal + 168
37 UIKitCore 0x135274 -[UIApplication _run] + 816
38 UIKitCore 0x100a28 UIApplicationMain + 336
39 APP1 0xa2ed0 main + 21 (AppDelegate.swift:21)
40 ??? 0x1aa889f08 (シンボルが不足しています)
From reviewing the crash log, it appears that the crash occurs inside UIKeyboardStateManager while handling keyboard or cursor updates.
Questions
Has anyone seen this specific crash pattern involving UIKeyboardStateManager?
Are there known UIKit or WebKit bugs related to UIKeyboardStateManager when continuously changing focus between text fields (especially in WKWebView)?
Any insights or workarounds would be greatly appreciated.
Thanks!
The code below is a test to trigger UI updates every 30 seconds. I'm trying to keep most work off main and only push to main once I have the string (which is cached). Why is updating SwiftUI 30 times per second so expensive? This code causes 10% CPU on my M4 Mac, but comment out the following line:
Text(model.timeString)
and it's 0% CPU. The reason why I think I have too much work on main is because of this from instruments. But I'm no instruments expert.
import SwiftUI
import UniformTypeIdentifiers
@main
struct RapidUIUpdateTestApp: App {
var body: some Scene {
DocumentGroup(newDocument: RapidUIUpdateTestDocument()) { file in
ContentView(document: file.$document)
}
}
}
struct ContentView: View {
@Binding var document: RapidUIUpdateTestDocument
@State private var model = PlayerModel()
var body: some View {
VStack(spacing: 16) {
Text(model.timeString) // only this changes
.font(.system(size: 44, weight: .semibold, design: .monospaced))
.transaction { $0.animation = nil } // no implicit animations
HStack {
Button(model.running ? "Pause" : "Play") {
model.running ? model.pause() : model.start()
}
Button("Reset") { model.seek(0) }
Stepper("FPS: \(Int(model.fps))", value: $model.fps, in: 10...120, step: 1)
.onChange(of: model.fps) { _, _ in model.applyFPS() }
}
}
.padding()
.onAppear { model.start() }
.onDisappear { model.stop() }
}
}
@Observable
final class PlayerModel {
// Publish ONE value to minimize invalidations
var timeString: String = "0.000 s"
var fps: Double = 30
var running = false
private var formatter: NumberFormatter = {
let f = NumberFormatter()
f.minimumFractionDigits = 3
f.maximumFractionDigits = 3
return f
}()
@ObservationIgnored private let q = DispatchQueue(label: "tc.timer", qos: .userInteractive)
@ObservationIgnored private var timer: DispatchSourceTimer?
@ObservationIgnored private var startHost: UInt64 = 0
@ObservationIgnored private var pausedAt: Double = 0
@ObservationIgnored private var lastFrame: Int = -1
// cache timebase once
private static let secsPerTick: Double = {
var info = mach_timebase_info_data_t()
mach_timebase_info(&info)
return Double(info.numer) / Double(info.denom) / 1_000_000_000.0
}()
func start() {
guard timer == nil else { running = true; return }
let desiredUIFPS: Double = 30 // or 60, 24, etc.
let periodNs = UInt64(1_000_000_000 / desiredUIFPS)
running = true
startHost = mach_absolute_time()
let t = DispatchSource.makeTimerSource(queue: q)
// ~30 fps, with leeway to let the kernel coalesce wakeups
t.schedule(
deadline: .now(),
repeating: .nanoseconds(Int(periodNs)), // 33_333_333 ns ≈ 30 fps
leeway: .milliseconds(30) // allow coalescing
)
t.setEventHandler { [weak self] in self?.tick() }
timer = t
t.resume()
}
func pause() {
guard running else { return }
pausedAt = now()
running = false
}
func stop() {
timer?.cancel()
timer = nil
running = false
pausedAt = 0
lastFrame = -1
}
func seek(_ seconds: Double) {
pausedAt = max(0, seconds)
startHost = mach_absolute_time()
lastFrame = -1 // force next UI update
}
func applyFPS() { lastFrame = -1 } // next tick will refresh string
// MARK: - Tick on background queue
private func tick() {
let s = now()
let str = formatter.string(from: s as NSNumber) ?? String(format: "%.3f", s)
let display = "\(str) s"
DispatchQueue.main.async { [weak self] in
self?.timeString = display
}
}
private func now() -> Double {
guard running else { return pausedAt }
let delta = mach_absolute_time() &- startHost
return pausedAt + Double(delta) * Self.secsPerTick
}
}
nonisolated struct RapidUIUpdateTestDocument: FileDocument {
var text: String
init(text: String = "Hello, world!") {
self.text = text
}
static let readableContentTypes = [
UTType(importedAs: "com.example.plain-text")
]
init(configuration: ReadConfiguration) throws {
guard let data = configuration.file.regularFileContents,
let string = String(data: data, encoding: .utf8)
else {
throw CocoaError(.fileReadCorruptFile)
}
text = string
}
func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
let data = text.data(using: .utf8)!
return .init(regularFileWithContents: data)
}
}
I'm looking for clarification on a SwiftUI performance point mentioned in the recent Optimize your app's speed and efficiency | Meet with Apple video.
(YouTube link not allowed, but the video is available on the Apple Developer channel.)
At the 1:48:50 mark, the presenter says:
Writing a value to the Environment doesn't only affect the views that read the key you're updating. It updates any view that reads from any Environment key. [abbreviated quote]
That statement seems like a big deal if your app relies heavily on Environment values.
Context
I'm building a macOS application with a traditional three-panel layout. At any given time, there are many views on screen, plus others that exist in the hierarchy but are currently hidden (for example, views inside tab views or collapsed splitters).
Nearly every major view reads something from the environment—often an @Observable object that acts as a service or provider.
However, there are a few relatively small values that are written to the environment frequently, such as:
The selected tab index
The currently selected object on a canvas
The Question
Based on the presenter's statement, I’m wondering:
Does writing any value to the environment really cause all views in the entire SwiftUI view hierarchy that read any environment key to have their body re-evaluated?
Do environment writes only affect child views, or do they propagate through the entire SwiftUI hierarchy?
Example:
View A
└─ View B
├─ View C
└─ View D
If View B updates an environment value, does that affect only C and D, or does it also trigger updates in A and B (assuming each view has at least one @Environment property)?
Possible Alternative
If all views are indeed invalidated by environment writes, would it be more efficient to “wrap” frequently-changing values inside an @Observable object instead of updating the environment directly?
// Pseudocode
@Observable final class SelectedTab {
var index: Int
}
ContentView()
.environment(\.selectedTab, selectedTab)
struct TabView: View {
@Environment(\.selectedTab) private var selectedTab
var body: some View {
Button("Action") {
// Would this avoid invalidating all views using the environment?
selectedTab.index = 1
}
}
}
Summary
From what I understand, it sounds like the environment should primarily be used for stable, long-lived objects—not for rapidly changing values—since writes might cause far more view invalidations than most developers realize.
Is that an accurate interpretation?
Follow-Up
In Xcode 26 / Instruments, is there a way to monitor writes to @Environment?
I'm experiencing an issue where my List selection (using EditButton) gets cleared when a confirmationDialog is presented, making it impossible to delete the selected items.
Environment:
Xcode 16.0.1
Swift 5
iOS 18 (targeting iOS 17+)
Issue Description:
When I select items in a List using EditButton and tap a delete button that shows a confirmationDialog, the selection is cleared as soon as the dialog appears. This prevents me from accessing the selected items to delete them.
Code:
State variables:
@State var itemsSelection = Set<Item>()
@State private var showDeleteConfirmation = false
List with selection:
List(currentItems, id: \.self, selection: $itemsSelection) { item in
NavigationLink(value: item) {
ItemListView(item: item)
}
}
.navigationDestination(for: Item.self) { item in
ItemViewDetail(item: item)
}
.toolbar {
ToolbarItem(placement: .primaryAction) {
EditButton()
}
}
Delete button with confirmation:
Button {
if itemsSelection.count > 1 {
showDeleteConfirmation = true
} else {
deleteItemsSelected()
}
} label: {
Image(systemName: "trash.fill")
.font(.system(size: 12))
.foregroundStyle(Color.red)
}
.padding(8)
.confirmationDialog(
"Delete?",
isPresented: $showDeleteConfirmation,
titleVisibility: .visible
) {
Button("Delete", role: .destructive) {
deleteItemsSelected()
}
Button("Cancel", role: .cancel) {}
} message: {
Text("Going to delete: \(itemsSelection.count) items?")
}
Expected Behavior:
The selected items should remain selected when the confirmationDialog appears, allowing me to delete them after confirmation.
Actual Behavior:
As soon as showDeleteConfirmation becomes true and the dialog appears, itemsSelection becomes empty (count = 0), making it impossible to delete the selected items.
What I've Tried:
Moving the confirmationDialog to different view levels
Checking if this is related to the NavigationLink interaction
Has anyone encountered this issue? Is there a workaround to preserve the selection when showing a confirmation dialog?
I’m seeing unexpected scroll behavior when embedding a LazyVStack with dynamically sized views inside a ScrollView.
Everything works fine when the item height is fixed (e.g. colored squares), but when I switch to text views with variable height, the scroll position jumps and glitches—especially when the keyboard appears or disappears. This only happens on iOS 26, it works fine on iOS 18.
Working version
struct Model: Identifiable {
let id = UUID()
}
struct ModernScrollView: View {
@State private var models: [Model] = []
@State private var scrollPositionID: String?
@State private var text: String = ""
@FocusState private var isFocused
// MARK: - View
var body: some View {
scrollView
.safeAreaInset(edge: .bottom) { controls }
.task { reset() }
}
// MARK: - Subviews
private var scrollView: some View {
ScrollView {
LazyVStack {
ForEach(models) { model in
SquareView(color: Color(from: model.id))
.id(model.id.uuidString)
}
}
.scrollTargetLayout()
}
.scrollPosition(id: $scrollPositionID)
.scrollDismissesKeyboard(.interactively)
.defaultScrollAnchor(.bottom)
.onTapGesture {
isFocused = false
}
}
private var controls: some View {
VStack {
HStack {
Button("Add to top") {
models.insert(contentsOf: makeModels(3), at: 0)
}
Button("Add to bottom") {
models.append(contentsOf: makeModels(3))
}
Button("Reset") {
reset()
}
}
HStack {
Button {
scrollPositionID = models.first?.id.uuidString
} label: {
Image(systemName: "arrow.up")
}
Button {
scrollPositionID = models.last?.id.uuidString
} label: {
Image(systemName: "arrow.down")
}
}
TextField("Input", text: $text)
.padding()
.background(.ultraThinMaterial, in: .capsule)
.focused($isFocused)
.padding(.horizontal)
}
.padding(.vertical)
.buttonStyle(.bordered)
.background(.regularMaterial)
}
// MARK: - Private
private func makeModels(_ count: Int) -> [Model] {
(0..<count).map { _ in Model() }
}
private func reset() {
models = makeModels(3)
}
}
// MARK: - Color+UUID
private extension Color {
init(from uuid: UUID) {
let hash = uuid.uuidString.hashValue
let r = Double((hash & 0xFF0000) >> 16) / 255.0
let g = Double((hash & 0x00FF00) >> 8) / 255.0
let b = Double(hash & 0x0000FF) / 255.0
self.init(red: abs(r), green: abs(g), blue: abs(b))
}
}
Not working version
When I replace the square view with a text view that generates random multiline text:
struct Model: Identifiable {
let id = UUID()
let text = generateRandomText(range: 1...5)
// MARK: - Utils
private static func generateRandomText(range: ClosedRange<Int>) -> String {
var result = ""
for _ in 0..<Int.random(in: range) {
if let sentence = sentences.randomElement() {
result += sentence
}
}
return result.trimmingCharacters(in: .whitespaces)
}
private static let sentences = [
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
"Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
"Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.",
"Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
]
}
and use it like this:
ForEach(models) { model in
Text(model.text)
.padding()
.multilineTextAlignment(.leading)
.background(Color(from: model.id))
.id(model.id.uuidString)
}
Then on iOS 26, opening the keyboard makes the scroll position jump unpredictably.
It is more visible if you play with the app, but I could not upload a video here.
Environment
Xcode 26.0.1 - Simulators and devices on iOS 26.0 - 18.0
Questions
Is there any known change in ScrollView / scrollPosition(id:) behavior on iOS 26 related to dynamic height content?
Am I missing something in the layout setup that makes this layout unstable with variable-height cells?
Is there a workaround or recommended approach for keeping scroll position stable when keyboard appears?
Hi Everyone,
I’m encountering a layout issue in SwiftUI starting with iOS 26 / Xcode 26 (also reproduced on iPadOS 26). I would like to see whether anyone else has seen the same behaviour, and if there’s any known workaround or fix from Apple.
Reproduction
Minimal code:
struct ContentView: View {
@State private var inputText: String = ""
var body: some View {
TextField("", text: $inputText)
.font(.system(size: 14, weight: .semibold))
.background(Capsule().foregroundStyle(.gray))
}
}
Environment:
Xcode: 26.1 (17B55)
Devices / Simulators: iOS 26.0, iOS 26.0.1, iOS 26.1 on iPhone 17 Pro Max; iPadOS 26 on iPad.
OS: iOS 26 / iPadOS 26
Observed behaviour
When the TextField is tapped for the first time (focus enters), its height suddenly decreases compared to the unfocused state.
After this initial focus-tap, subsequent unfocus/focus cycles preserve the height (i.e., height remains “normal” and stable).
Prior to iOS 26 (i.e., in older iOS versions) I did not observe this behaviour — same code worked fine.
I have not explicitly set .frame(height:) or extra padding, and I’m relying on the default intrinsic height + the Capsule background.
Work-arounds
Adding .frame(height: X) (fixed height) removes the issue (height stable).
Thanks in advance for any feedback!
[Submitted as FB20978913]
When using .navigationTransition(.zoom) with a fullScreenCover, deleting the source item from the destination view causes a brief black flash during the dismiss animation. This is only visible in Light mode.
REPRO STEPS
Build and run the sample code below.
Set the device to Light mode.
Tap any row to open its detail view.
In the detail view, tap Delete.
Watch the dismiss animation as the list updates.
EXPECTED
The zoom transition should return smoothly to the list with no dark or black flash.
ACTUAL
A visible black flash appears over the deleted row during the collapse animation. It starts black, shortens, and fades out in sync with the row-collapse motion. The flash lasts about five frames and is consistently visible in Light mode.
NOTES
Occurs only when deleting from the presented detail view.
Does not occur when deleting directly from the list.
Does not occur or is not visible in Dark mode.
Reproducible on both simulator and device.
Removing .navigationTransition(.zoom) or using .sheet instead of .fullScreenCover avoids the issue.
SYSTEM INFO
Version 26.1 (17B55)
iOS 26.1
Devices: iPhone 17 Pro simulator, iPhone 13 Pro hardware
Appearance: Light
Reproducible 100% of the time
SAMPLE CODE
import SwiftUI
struct ContentView: View {
@State private var items = (0..<20).map { Item(id: $0, title: "Item \($0)") }
@State private var selectedItem: Item?
@Namespace private var ns
var body: some View {
NavigationStack {
List {
ForEach(items) { item in
Button {
selectedItem = item
} label: {
HStack {
Text(item.title)
Spacer()
}
.padding(.vertical, 8)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.matchedTransitionSource(id: item.id, in: ns)
.swipeActions {
Button(role: .destructive) {
delete(item)
} label: {
Label("Delete", systemImage: "trash")
}
}
}
}
.listStyle(.plain)
.navigationTitle("Row Delete Issue")
.navigationSubtitle("In Light mode, tap item then tap Delete to see black flash")
.fullScreenCover(item: $selectedItem) { item in
DetailView(item: item, ns: ns) {
delete(item)
selectedItem = nil
}
}
}
}
private func delete(_ item: Item) {
withAnimation {
items.removeAll { $0.id == item.id }
}
}
}
struct DetailView: View {
let item: Item
let ns: Namespace.ID
let onDelete: () -> Void
@Environment(\.dismiss) private var dismiss
var body: some View {
NavigationStack {
VStack(spacing: 30) {
Text(item.title)
Button("Delete", role: .destructive, action: onDelete)
}
.navigationTitle("Detail")
.toolbar {
Button("Close") { dismiss() }
}
}
.navigationTransition(.zoom(sourceID: item.id, in: ns))
}
}
struct Item: Identifiable, Hashable {
let id: Int
let title: String
}
SCREEN RECORDING
In my AppKit app I have a an outline view where each cell has a title (NSTextField), image view (NSImageView), and 4 NSButtons that are essentially static badges (their .bezelStyle is set to .badge). I’ve seeing very low performance when doing quick reloads in successions, for example when filtering data. My app is built on macOS Tahoe.
Profiling the app in instruments I can see that each initialization takes more than 70ms. Does this make sense?
Thanks!
Topic:
UI Frameworks
SubTopic:
AppKit
What is the correct way to implement scrolling in a looong list that uses ScrollView and LazyVstack
Imagine I have some api that returns a longs list of comments with replies
The basic usecase is to scroll to the bottom(to the last comment) Most of the time this works fine
But, imagine some of the comments have many replies like 35 or more (or even 300)
User expands replies for the first post, then presses scroll to bottom.
The scrollbar reaches the bottom and I see the blank screen.
Sometimes the scrollbar may jump for a while before lazyvstack finishes loading or until I manually scroll up a bit or all the way up and down
What should I do in this case? Is this the swiftui performance problem that has no cure?
Abstract example:
ScrollViewReader { proxy in
ScrollView {
LazyVStack {
ForEach(comments) { comment in
CommentView(comment: comment)
.id("comment-\(comment.id)")
}
}
}
}
struct CommentView: View {
let comment: Comment
@State var isExpanded = false
var body: some View {
VStack {
Text(comment.text)
if isExpanded {
RepliesView(replies: comment.replies) // 35-300+ replies
}
}
}
}
...
scroll
proxy.scrollTo("comment-\(lastComment.id)", anchor: .bottom)