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.

Posts under General subtopic

Post

Replies

Boosts

Views

Activity

sandbox causes the input method switch to fail to take effect
Dear Apple developers: Hello, recently I want to develop an application for macos that automatically switches input methods. The function is that when you switch applications, it can automatically switch to the input method you set, thus eliminating the trouble of manual switching. All the functions have been implemented, but only when the sandbox is closed. When I opened the sandbox, I found a very strange phenomenon. Suppose wechat was set to the Chinese input method. When I switched to wechat, wechat automatically got the focus of the input box. The input method icon in the upper right corner of the screen had actually switched successfully, but when I actually input, it was still the previous input method. If you switch to an application that does not have a built-in focus, the automatic switching of the input method will take effect when you click the input box with the mouse to regain the focus. This phenomenon is too difficult for my current technical level. I have tried many methods but none of them worked. I hope the respected experts can offer some ideas. Below is a snippet of the code switching I provided: DispatchQueue. Main. AsyncAfter (deadline: now () + 0.1) { let result = TISSelectInputSource(inputSource) if result == noErr { print(" Successfully switched to input method: \(targetInputMethod)") } else { print(" Input method switch failed. Error code: \(result)") } // Verify the switching result if let newInputSource = getCurrentInputSource() { print(" Switched input method: (newInputSource)") } } When the sandbox is opened, the synchronous switching does not take effect. The input method icon in the status bar will flash for a moment, unable to compete with system events. Even if it is set to DispatchQueue.main.async, it still does not work. It seems that there is a timing issue with the input method switching. Development environment macOS version: 15.4.1 Xcode version: 16.2
0
0
96
Jul ’25
keyboard crash
My app encountered a crash problem. The analysis stack seems to be related to the keyboard. The system keyboard code is unresponsive for a long time until it crash. The feature of the stack, BrowserEngineKit, seems to indicate the webview scene. Xcode debugging found that tap the input box on the webview page can reproduce the same stack as the crash, but the crash cannot be reproduced. I noticed a feedback link https://developer.apple.com/forums/thread/784718, which is the same as the top of the crash stack I encountered, so the root cause of the problem may be similar, caused by the locking operation related to UIKeyboardTaskQueue. Hope to give some suggestions. Thanks. crash log: Incident Identifier: 39E3AFE6-43B1-4DE6-AC2B-D62C5EC89752 CrashReporter Key: AppleMetricKit Hardware Model: iPhone17,2 Process: iAliexpress Code Type: ARM-64 Parent Process: ? [1] Date/Time: 2025-07-02 22:59:00 Launch Time: Unknown OS Version: iPhone OS 18.1.1 (22B91) Report Version: 104 Exception Type: EXC_CRASH Exception Codes: KERN_SUCCESS Triggered by Thread: 0 Application Specific Information: <RBSTerminateContext| domain:10 code:0x8BADF00D explanation:scene-update watchdog transgression: app<com.alibaba.iAliexpress(A182346C-2A09-4082-9AAE-0EC7A1A1B5AB)>:2263 exhausted real (wall clock) time allowance of 10.00 seconds ProcessVisibility: Unknown ProcessState: Running WatchdogEvent: scene-update WatchdogVisibility: Background WatchdogCPUStatistics: ( "Elapsed total CPU time (seconds): 15.280 (user 9.430, system 5.850), 25% CPU", "Elapsed application CPU time (seconds): 0.210, 0% CPU" ) reportType:CrashLog maxTerminationResistance:Interactive> Thread 0 Crashed: 0 libsystem_kernel.dylib 0x00000001ea7f7f90 __psynch_cvwait :8 (in libsystem_kernel.dylib) 1 libsystem_pthread.dylib 0x000000022296aa7c _pthread_cond_wait :1248 (in libsystem_pthread.dylib) 2 Foundation 0x000000019908fa9c -[NSCondition waitUntilDate:] :132 (in Foundation) 3 Foundation 0x000000019908bea8 -[NSConditionLock lockWhenCondition:beforeDate:] :80 (in Foundation) 4 UIKitCore 0x000000019d05cbb4 -[UIKeyboardTaskQueue lockWhenReadyForMainThread] :784 (in UIKitCore) 5 UIKitCore 0x000000019d05c85c -[UIKeyboardTaskQueue waitUntilAllTasksAreFinished] :160 (in UIKitCore) 6 UIKitCore 0x000000019d56720c -[_UIKeyboardStateManager prepareForSelectionChange] :128 (in UIKitCore) 7 UIKitCore 0x000000019d5674f4 -[_UIKeyboardStateManager selectionWillChange:] :72 (in UIKitCore) 8 BrowserEngineKit 0x0000000257671688 -[BETextInteraction selectionWillChange:] :84 (in BrowserEngineKit) 9 UIKitCore 0x000000019d75d654 -[UIAsyncTextInteraction selectionWillChange:] :68 (in UIKitCore) 10 UIKitCore 0x000000019dbae374 -[_UIKeyboardTextSelectionController beginSelectionChange] :64 (in UIKitCore) 11 UIKitCore 0x000000019df5fed0 -[UITextSelectionInteraction tappedToPositionCursorWithGesture:atPoint:granularity:completionHandler:] :476 (in UIKitCore) 12 UIKitCore 0x000000019df5f948 -[UITextSelectionInteraction _checkForRepeatedTap:gestureLocationOut:] :1072 (in UIKitCore) 13 UIKitCore 0x000000019df60488 -[UITextSelectionInteraction _handleMultiTapGesture:] :852 (in UIKitCore) 14 UIKitCore 0x000000019cf879cc -[UIApplication sendAction:to:from:forEvent:] :100 (in UIKitCore) 15 UIKitCore 0x000000019d84ce98 -[UITextMultiTapRecognizer onStateUpdate:] :280 (in UIKitCore) 16 UIKitCore 0x000000019cfb6ac4 -[UIGestureRecognizerTarget _sendActionWithGestureRecognizer:] :128 (in UIKitCore) 17 UIKitCore 0x000000019cfb6934 _UIGestureRecognizerSendTargetActions :92 (in UIKitCore) 18 UIKitCore 0x000000019cfb66f4 _UIGestureRecognizerSendActions :284 (in UIKitCore) 19 UIKitCore 0x000000019cc69b28 -[UIGestureRecognizer _updateGestureForActiveEvents] :572 (in UIKitCore) 20 UIKitCore 0x000000019cc3b724 _UIGestureEnvironmentUpdate :2488 (in UIKitCore) 21 UIKitCore 0x000000019cd2fa00 -[UIGestureEnvironment _deliverEvent:toGestureRecognizers:usingBlock:] :336 (in UIKitCore) 22 UIKitCore 0x000000019cecffe4 -[UIGestureEnvironment _updateForEvent:window:] :188 (in UIKitCore) 23 UIKitCore 0x000000019cecf3c8 -[UIWindow sendEvent:] :2948 (in UIKitCore) 24 iAliexpress 0x0000000104e92000 -[UIWindow(AliHA) aliHASwizzledSendEvent:] UIWindow+AliHA.m:18 (in iAliexpress) 25 UIKitCore 0x000000019cd63b70 -[UIApplication sendEvent:] :376 (in UIKitCore) 26 iAliexpress 0x0000000104e91c84 -[UIApplication(SPM) alg_sendEvent:] AFSPMManager.m:0 (in iAliexpress) 27 UIKitCore 0x000000019cd6409c __dispatchPreprocessedEventFromEventQueue :1048 (in UIKitCore) 28 UIKitCore 0x000000019cd6df3c __processEventQueue :5696 (in UIKitCore) 29 UIKitCore 0x000000019cc66c60 updateCycleEntry :160 (in UIKitCore) 30 UIKitCore 0x000000019cc649d8 _UIUpdateSequenceRun :84 (in UIKitCore) 31 UIKitCore 0x000000019cc64628 schedulerStepScheduledMainSection :172 (in UIKitCore) 32 UIKitCore 0x000000019cc6559c runloopSourceCallback :92 (in UIKitCore) 33 CoreFoundation 0x000000019a434328 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ :28 (in CoreFoundation) 34 CoreFoundation 0x000000019a4342bc __CFRunLoopDoSource0 :176 (in CoreFoundation) 35 CoreFoundation 0x000000019a431dc0 __CFRunLoopDoSources0 :244 (in CoreFoundation) 36 CoreFoundation 0x000000019a430fbc __CFRunLoopRun :840 (in CoreFoundation) 37 CoreFoundation 0x000000019a430830 CFRunLoopRunSpecific :588 (in CoreFoundation) 38 GraphicsServices 0x00000001e64101c4 GSEventRunModal :164 (in GraphicsServices) 39 UIKitCore 0x000000019cf96eb0 -[UIApplication _run] :816 (in UIKitCore) 40 UIKitCore 0x000000019d0455b4 UIApplicationMain :340 (in UIKitCore) 41 iAliexpress 0x0000000104e9b0b8 _main main.m:17 (in iAliexpress) 42 dyld 0x00000001bfe1eec8 start :2724 (in dyld)
2
1
156
Jul ’25
Ask Each Time on macOS doesn't not allow empty selection
Hello! I'm facing a strange behavior on macOS related to Ask Each Time, which works fine on iOS. I've an App Intent that declares a parameter like so: @Parameter( title: "Tags", description: "Tags to add to the link.", optionsProvider: TagsOptionsProvider() ) var tags: [String]? The TagsOptionProvider is like this: struct TagsOptionsProvider: DynamicOptionsProvider { @Dependency private var modelCoordinator: ModelCoordinator @MainActor func results() async throws -> [String] { return modelCoordinator.tags().compactMap { $0.name } } } Now, the issue comes if I create a shortcut where for the tags parameter the user selects the magic variable Ask Each Time. On iOS, when the user is presented with the selector, they can simply tap 'Done' without selecting any value (the user does not want to include any tag). The problem is that on macOS the 'Done' button is disabled if there's no selection. See both behaviors: iOS: macOS: Question: Is there a way to let macOS continue even if the user doesn't select any of the available options like on iOS? I've tried declaring the tags para meter as Optional (like on the screenshot) and non-optional, both cases show the same behavior. Environment: iOS 18.5 macOS 15.5
1
0
234
Jul ’25
Cursor position sync between IOS touch screen and app textview.
The app puts button values into a text view area and controls the cursor. Upon an IOS touch screen, cut or paste, the IOS cursor loses sync with the app cursor causing an address out of bounds and fails. The IOS cut or paste changes the cursor position and the text.endIndex address by shrinking or expanding the text field. IOS doesn't know about the app cursorPosition. If IOS could update the app cursor position and the text.endIndex position would solve the problem. Or if the app knew about the IOS change could update the app cursor position and the text.endIndex. The current work around is the user sets the cursor to the text.startIndex using an app navigating button before the touch screen. The app does not fail. The user then navigates the cursor using arrow buttons to another position. To see this happen download the free SummaGramIPAD Trial.(13") TSIs have been requested with engineer suggestions for well over one year. I hope someone could figure this out. I just finished SummaGram iPhone and would like to host it. Thanks for your help. Charlie
0
0
42
Jul ’25
Cursor Misalignment When Selecting List Options – macOS Tahoe 26.0 Developer Beta 2
Since updating my MacBook Air to macOS Tahoe 26.0 Developer Beta 2, I’ve encountered a persistent cursor misalignment issue: When interacting with lists or contextual menus, the cursor’s visual position does not align with what it actually selects. The system registers the cursor slightly above where it appears, causing clicks to select the wrong option or fail to register. As a temporary workaround, I can sometimes position the cursor off-target and press Enter to select, but this is a frustrating and inefficient workaround. The issue persists after a restart and appears across multiple areas of the OS: Right-clicking an app in the Dock to open the contextual menu → cursor highlights an incorrect item relative to its position. In System Settings menus. Even on the Feedback Assistant site when selecting issue categories. Steps to Reproduce: 1️⃣ Update to macOS Tahoe 26.0 Developer Beta 2 on MacBook Air. 2️⃣ Right-click on any open application in the Dock. 3️⃣ Attempt to select an option from the list that appears. 4️⃣ Observe that the cursor highlights or interacts with a different option than where the cursor is visibly located. Notes: Issue is consistent across reboots. Affects workflow and general navigation. Temporary workaround using keyboard navigation is insufficient for productivity. FB Number: FB18531124 If others are seeing this as well, please confirm below so Apple can prioritize investigation.
2
1
120
Jul ’25
Tesflight and Firebase Auth issues on AppResume
I am working on my app and encountering issues when promoting my app to TestFlight, after I download the app on testflight on my device I am able to log in, however if I minimize the app and try to re-open it again, I get a blank screen, after that, I have tried removing app and reinstalling but no sucess there. I have compiled the app in release mode in xcode directly (Scheme > Release) and was able to run the app normally and no isues observed in logm only when promoted to testflight for testing App stack: Flutter (built using latest Flutterflow build 6.0.34) Firebase backend
Topic: UI Frameworks SubTopic: General
0
0
106
Jul ’25
A Summary of the WWDC25 Group Lab - UI Frameworks
At WWDC25 we launched a new type of Lab event for the developer community - Group Labs. A Group Lab is a panel Q&A designed for a large audience of developers. Group Labs are a unique opportunity for the community to submit questions directly to a panel of Apple engineers and designers. Here are the highlights from the WWDC25 Group Lab for UI Frameworks. How would you recommend developers start adopting the new design? Start by focusing on the foundational structural elements of your application, working from the "top down" or "bottom up" based on your application's hierarchy. These structural changes, like edge-to-edge content and updated navigation and controls, often require corresponding code modifications. As a first step, recompile your application with the new SDK to see what updates are automatically applied, especially if you've been using standard controls. Then, carefully analyze where the new design elements can be applied to your UI, paying particular attention to custom controls or UI that could benefit from a refresh. Address the large structural items first then focus on smaller details is recommended. Will we need to migrate our UI code to Swift and SwiftUI to adopt the new design? No, you will not need to migrate your UI code to Swift and SwiftUI to adopt the new design. The UI frameworks fully support the new design, allowing you to migrate your app with as little effort as possible, especially if you've been using standard controls. The goal is to make it easy to adopt the new design, regardless of your current UI framework, to achieve a cohesive look across the operating system. What was the reason for choosing Liquid Glass over frosted glass, as used in visionOS? The choice of Liquid Glass was driven by the desire to bring content to life. The see-through nature of Liquid Glass enhances this effect. The appearance of Liquid Glass adapts based on its size; larger glass elements look more frosted, which aligns with the design of visionOS, where everything feels larger and benefits from the frosted look. What are best practices for apps that use customized navigation bars? The new design emphasizes behavior and transitions as much as static appearance. Consider whether you truly need a custom navigation bar, or if the system-provided controls can meet your needs. Explore new APIs for subtitles and custom views in navigation bars, designed to support common use cases. If you still require a custom solution, ensure you're respecting safe areas using APIs like SwiftUI's safeAreaInset. When working with Liquid Glass, group related buttons in shared containers to maintain design consistency. Finally, mark glass containers as interactive. For branding, instead of coloring the navigation bar directly, consider incorporating branding colors into the content area behind the Liquid Glass controls. This creates a dynamic effect where the color is visible through the glass and moves with the content as the user scrolls. I want to know why new UI Framework APIs aren’t backward compatible, specifically in SwiftUI? It leads to code with lots of if-else statements. Existing APIs have been updated to work with the new design where possible, ensuring that apps using those APIs will adopt the new design and function on both older and newer operating systems. However, new APIs often depend on deep integration across the framework and graphics stack, making backward compatibility impractical. When using these new APIs, it's important to consider how they fit within the context of the latest OS. The use of if-else statements allows you to maintain compatibility with older systems while taking full advantage of the new APIs and design features on newer systems. If you are using new APIs, it likely means you are implementing something very specific to the new design language. Using conditional code allows you to intentionally create different code paths for the new design versus older operating systems. Prefer to use if #available where appropriate to intentionally adopt new design elements. Are there any Liquid Glass materials in iOS or macOS that are only available as part of dedicated components? Or are all those materials available through new UIKit and AppKit views? Yes, some variations of the Liquid Glass material are exclusively available through dedicated components like sliders, segmented controls, and tab bars. However, the "regular" and "clear" glass materials should satisfy most application requirements. If you encounter situations where these options are insufficient, please file feedback. If I were to create an app today, how should I design it to make it future proof using Liquid Glass? The best approach to future-proof your app is to utilize standard system controls and design your UI to align with the standard system look and feel. Using the framework-provided declarative API generally leads to easier adoption of future design changes, as you're expressing intent rather than specifying pixel-perfect visuals. Pay close attention to the design sessions offered this year, which cover the design motivation behind the Liquid Glass material and best practices for its use. Is it possible to implement your own sidebar on macOS without NSSplitViewController, but still provide the Liquid Glass appearance? While technically possible to create a custom sidebar that approximates the Liquid Glass appearance without using NSSplitViewController, it is not recommended. The system implementation of the sidebar involves significant unseen complexity, including interlayering with scroll edge effects and fullscreen behaviors. NSSplitViewController provides the necessary level of abstraction for the framework to handle these details correctly. Regarding the SceneDelagate and scene based life-cycle, I would like to confirm that AppDelegate is not going away. Also if the above is a correct understanding, is there any advice as to what should, and should not, be moved to the SceneDelegate? UIApplicationDelegate is not going away and still serves a purpose for application-level interactions with the system and managing scenes at a higher level. Move code related to your app's scene or UI into the UISceneDelegate. Remember that adopting scenes doesn't necessarily mean supporting multiple scenes; an app can be scene-based but still support only one scene. Refer to the tech note Migrating to the UIKit scene-based life cycle and the Make your UIKit app more flexible WWDC25 session for more information.
Topic: UI Frameworks SubTopic: General
0
0
532
Jun ’25
Apple CarPlay Notification Custom Actions
I am setting up push notifications in CarPlay and when the user taps on notification from infotainment screen, it should open the app and a CPAlertTemplate should be presented. How can I achieve this? since I'm unable to get a trigger on the didReceiveNotificationResponse so handle some custom actions in between.
0
1
42
Jun ’25
Changes to CarPlay maps Application scene
I am looking at the demo code for CarPlay Maps app - https://developer.apple.com/documentation/carplay/integrating-carplay-with-your-navigation-app This worked in IOS 18 but now on IOS26 it doesn't work, eg the map in the CarPlay app no longer shows up. I don't see any docks to say what has changed, I wonder if anyone has any ideas?
0
0
90
Jun ’25
SF Symbols 6 app does not export 'Can Rotate' property of a layer
The SF Symbols app 6.0 (99) does not export the ‘Can Rotate’ property of layers when exporting a symbol via File > Export Symbol. Without this, all the new fantastic edit functions in the app related to rotating in SF Symbols is completely useless. This issue with the SF Symbols 6 app can be reproduced by exporting a rotatable symbol like fan.desk, and then by importing the result as custom symbol. When inspecting ‘Group 1’ of the imported symbol, it is no longer marked as rotatable. SF Symbols app 6.0 is still in beta, but hasn't been updated since 10 June. Hopefully this bug will be solved in the release version, or earlier. Does anyone know how to manually add the missing rotation info to the exported SVG file? In case an Apple engineer reads this: FB13916635
4
2
683
Jun ’25
Accessibility Permission In Sandbox For Keyboard
Hello! My question is about 1) if we can use any and or all accessibility features within a sandboxed app and 2) what steps we need to take to do so. Using accessibility permissions, my app was working fine in Xcode. It used NSEvent.addGlobalMonitorForEvents and localMoniter, along with CGEvent.tapCreate. However, after downloading the same app from the App Store, the code was not working. I believe this was due to differences in how permissions for accessibility are managed in Xcode compared to production. Is it possible for my app to get access to all accessibility features, while being distributed on the App Store though? Do I need to add / request any special entitlements like com.apple.security.accessibility? Thanks so much for the help. I have done a lot of research on this online but found some conflicting information, so wanted to post here for a clear answer.
6
0
123
Jun ’25
Creating UI instance using 'XML' like data at runtime
In windows there is a support for generating Xaml strings at runtime for the UI artefact and use it on the main thread for loading the Xaml strings with properties and creating the UI artefact. Below is a code example for it. static void createxaml(hstring & str) { str = LR"( <Button xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation Name="MyButton" Content="Click Me" Width="200" Height="60" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="18" FontFamily="Segoe UI" Foreground="White" )"; } { hstring xaml; createxaml(xaml); Button obj = XamlReader::Load(xaml).as<Button>(); } My question is, Is there similar support available in uikit to create ui instances like UIButton. Is there some native support from apple that allows us to create a button object using an XML like string?
Topic: UI Frameworks SubTopic: General Tags:
2
0
67
Jun ’25
Can `UIApplication.shared.setAlternateIconName` use .icon file?
I’m updating my app’s alternate icons using UIApplication.shared.setAlternateIconName, and I noticed that in iOS 26, Xcode now supports the new .icon file format for App Icons. Is it possible to reference .icon files directly for alternate icons? Or does setAlternateIconName still only support traditional .png assets inside the AppIcon set? I couldn’t find any documentation confirming this either way, and I want to ensure compatibility with the new format while supporting alternate icons. Any clarification or Apple documentation link would be greatly appreciated!
0
0
173
Jun ’25
iOS 26 button glitch
Im just wondering with the new iOS 26 developer beta 2 has anyone else had the button glitch? its like the buttons glitch out and its just weird. You have to hold the liquid glass and be able to move the app windows for it to happen. you also can’t see it happen on screen recording for some reason. It recently happen to me when I was on a call with apple support for a different reason and the buttons that were highlighted were the only ones glitching out.
Topic: UI Frameworks SubTopic: General
5
1
502
Jun ’25
iOS18.1以降でのアプリレイアウト崩れに関して
iOS18.0以前では発生していなかったアプリのレイアウト崩れが発生しており、これはOS起因のバグなのか否かをご教示いただきたいです。 【事象】 iOS18.0以前では発生していなかった、右上に表示していたアイコンが真ん中に来ているといったアプリのレイアウト崩れが発生しております。 【原因調査】 ソースを確認したところ、 親要素のCSS内にあるui-btn-textのdisplayが、上記事象が発生しているOS(現在で確認できているのは18.4.1と18.5)だと 「display: block」もしくは「display: inline-block」となっていない場合横幅がない状態として判定されています。 その為「position:absolute」かつ、「right: XXpx」という指定を行った場合、iOS18.0以前では親要素の右端から「XXpx」ずれた位置に配置される形となりますが、事象が発生しているOSでは(横幅が0として判定されるため)親要素の左端から「XXpx」ずれた位置に配置される形となっております。 【質問】 これはOS起因のバグなのか仕様変更なのか確認いただきたいです。
Topic: UI Frameworks SubTopic: General
0
0
54
Jun ’25
CIContext sporadically crashes on macOS 15.4/15.5, iOS 18.4/18.5
We have some rather old code that worked for many years, but recently started to crash sporadically here: The crash looks like this: or Our code is called from many threads concurrently, but as said it worked without any issues until recently. I've found the apparently same crash on iOS at this Reddit post: https://www.reddit.com/r/iOSProgramming/comments/1kle4h4/ios_185_doesnt_fix_cicontext_rendering_crash/ Recap: we believe it started on macOS 18.4 and is still on macOS 18.5. But maybe it was already on macOS 18.3. This matches the observation in the Reddit post well. Should we create a feedback with sysdiagnose? Thanks! :)
13
4
334
Jun ’25
Is configuration-style API (like UIButton.configuration) available for other UIKit or AppKit components?
In UIKit, UIButton provides a configuration property which allows us to create and customize a UIButton.Configuration instance independently (on a background thread or elsewhere) and later assign it to a UIButton instance. This separation of configuration and assignment is very useful for clean architecture and performance optimization. Questions: Is this configuration-style pattern (creating a configuration object separately and assigning it later) available or planned for other UIKit components such as UILabel, UITextField, UISlider, etc.? Similarly, in AppKit on macOS, are there any components (e.g. NSButton, NSTextField) that support a comparable configuration object mechanism that can be used the same way — constructed separately and assigned to the view later? This would help in building consistent configuration-driven UI frameworks across Apple platforms. Any insight or official guidance would be appreciated.
0
0
61
Jun ’25
Ios 26 Developer Beta 2 Bugs
Hello Apple Developers and Software enginers Developers I am hee to report two UI Bugs that I have ran in to on version 2 Beta First bug in the UI is when I press and hold the side power button and the volume up button their is a weird animation happening since I am unable to record the lock screen due to security and privacy reason The 3 options show up power off phone something else and something else and then cancel
Topic: UI Frameworks SubTopic: General
1
0
111
Jun ’25
SwiftData .deny deleteRule not working
I tried to use the .deny deleteRule but it seems to have no effect. The toolbar button adds an item with a relationship to a category to the context. Swiping on the category deletes the category even though an item is referencing the category. There is also no error thrown when saving the context. It is as if the deleteRule was not there. For other deleteRules like .cascade, the provided sample code works as expected. import SwiftUI import SwiftData @Model class Category { var name: String @Relationship(deleteRule: .deny) var items: [Item] = [] init(name: String) { self.name = name } } @Model class Item { var name: String var category: Category? init(name: String, category: Category) { self.name = name self.category = category } } struct DenyDeleteRule: View { @Environment(\.modelContext) private var modelContext @Query private var categories: [Category] @Query private var items: [Item] var body: some View { List { Section("Items") { ForEach(items) { item in Text(item.name) } } Section("Categories") { ForEach(categories) { category in VStack(alignment: .leading) { Text(category.name).bold() ForEach(category.items) { item in Text("• \(item.name)") } } } .onDelete(perform: deleteCategory) } } .toolbar { Button("Add Sample") { let category = Category(name: "Sample") let item = Item(name: "Test Item", category: category) modelContext.insert(item) } } } func deleteCategory(at offsets: IndexSet) { for index in offsets { let category = categories[index] modelContext.delete(category) do { try modelContext.save() } catch { print(error) } } } } #Preview { NavigationStack { DenyDeleteRule() } .modelContainer(for: [Item.self, Category.self], inMemory: true) }
1
0
56
Jun ’25