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

SwiftUI Documentation

Posts under SwiftUI subtopic

Post

Replies

Boosts

Views

Activity

A Summary of the WWDC25 Group Lab - SwiftUI
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 SwiftUI. What's your favorite new feature introduced to SwiftUI this year? The new rich text editor, a collaborative effort across multiple Apple teams. The safe area bar, simplifying the management of scroll view insets, safe areas, and overlays. NavigationLink indicator visibility control, a highly requested feature now available and back-deployed. Performance improvements to existing components (lists, scroll views, etc.) that come "for free" without requiring API adoption. Regarding performance profiling, it's recommended to use the new SwiftUI Instruments tool when you have a good understanding of your code and notice a performance drop after a specific change. This helps build a mental map between your code and the profiler's output. The "cause-and-effect graph" in the tool is particularly useful for identifying what's triggering expensive view updates, even if the issue isn't immediately apparent in your own code. My app is primarily UIKit-based, but I'm interested in adopting some newer SwiftUI-only scene types like MenuBarExtra or using SwiftUI-exclusive features. Is there a better way to bridge these worlds now? Yes, "scene bridging" makes it possible to use SwiftUI scenes from UIKit or AppKit lifecycle apps. This allows you to display purely SwiftUI scenes from your existing UIKit/AppKit code. Furthermore, you can use SwiftUI scene-specific modifiers to affect those scenes. Scene bridging is a great way to introduce SwiftUI into your apps. This also allows UIKit apps brought to Vision OS to integrate volumes and immersive spaces. It's also a great way to customize your experience with Assistive Access API. Can you please share any bad practices we should avoid when integrating Liquid Glass in our SwiftUI Apps? Avoid these common mistakes when integrating liquid glass: Overlapping Glass: Don't overlap liquid glass elements, as this can create visual artifacts. Scrolling Content Collisions: Be cautious when using liquid glass within scrolling content to prevent collisions with toolbar and navigation bar glass. Unnecessary Tinting: Resist the urge to tint the glass for branding or other purposes. Liquid glass should primarily be used to draw attention and convey meaning. Improper Grouping: Use the GlassEffectContainer to group related glass elements. This helps the system optimize rendering by limiting the search area for glass interactions. Navigation Bar Tinting: Avoid tinting navigation bars for branding, as this conflicts with the liquid glass effect. Instead, move branding colors into the content of the scroll view. This allows the color to be visible behind the glass at the top of the view, but it moves out of the way as the user scrolls, allowing the controls to revert to their standard monochrome style for better readability. Thanks for improving the performance of SwiftUI List this year. How about LazyVStack in ScrollView? Does it now also reuse the views inside the stack? Are there any best practices for improving the performance when using LazyVStack with large number of items? SwiftUI has improved scroll performance, including idle prefetching. When using LazyVStack with a large number of items, ensure your ForEach returns a static number of views. If you're returning multiple views within the ForEach, wrap them in a VStack to signal to SwiftUI that it's a single row, allowing for optimizations. Reuse is handled as an implementation detail within SwiftUI. Use the performance instrument to identify expensive views and determine how to optimize your app. If you encounter performance issues or hitches in scrolling, use the new SwiftUI Instruments tool to diagnose the problem. Implementing the new iOS 26 tab bar seems to have very low contrast when darker content is underneath, is there anything we should be doing to increase the contrast for tab bars? The new design is still in beta. If you're experiencing low contrast issues, especially with darker content underneath, please file feedback. It's generally not recommended to modify standard system components. As all apps on the platform are adopting liquid glass, feedback is crucial for tuning the experience based on a wider range of apps. Early feedback, especially regarding contrast and accessibility, is valuable for improving the system for all users. If I’m starting a new multi-platform app (iOS/iPadOS/macOS) that will heavily depend on UIKit/AppKit for the core structure and components (split, collection, table, and outline views), should I still use SwiftUI to manage the app lifecycle? Why? Even if your new multi-platform app heavily relies on UIKit/AppKit for core structure and components, it's generally recommended to still use SwiftUI to manage the app lifecycle. This sets you up for easier integration of SwiftUI components in the future and allows you to quickly adopt new SwiftUI features. Interoperability between SwiftUI and UIKit/AppKit is a core principle, with APIs to facilitate going back and forth between the two frameworks. Scene bridging allows you to bring existing SwiftUI scenes into apps that use a UIKit lifecycle, or vice versa. Think of it not as a binary choice, but as a mix of whatever you need. I’d love to know more about the matchedTransitionSource API you’ve added - is it a native way to have elements morph from a VStack to a sheet for example? What is the use case for it? The matchedTransitionSource API helps connect different views during transitions, such as when presenting popovers or other presentations from toolbar items. It's a way to link the user interaction to the presented content. For example, it can be used to visually connect an element in a VStack to a sheet. It can also be used to create a zoom effect where an element appears to enlarge, and these transitions are fully interactive, allowing users to swipe. It creates a nice, polished experience for the user. Support for this API has been added to toolbar items this year, and it was already available for standard views.
Topic: UI Frameworks SubTopic: SwiftUI
1
0
1.2k
Jun ’25
Live Q&A Summary - SwiftUI foundations: Build great apps with SwiftUI
Here’s a recap of the Live Q&A for SwiftUI foundations: Build great apps with SwiftUI. If you participated and asked questions, thank you for coming and participating! If you weren’t able to join us live we hope this recap is useful Where can I watch the VOD? Is the sample code “Wishlist” that was shown available for download? You can view the replay of the entire event here https://www.youtube.com/watch?v=Z3vloOtZLkQ The sample code for the Wishlist app will be made available in the coming weeks on the Apple Developer website, we'll send an update via email when it is available. What are the best practices when it comes to building complex navigations in SwiftUI? The developer website has documentation on navigation style best practices. Explore navigation basics like NavigationStack and TabView to get a ground-up understanding. For documentation on navigation APIs see Navigation. How can I integrate UIKit with my SwiftUI app? What about adding SwiftUI into my UIKit app? See UIKit integration: Add UIKit views to your SwiftUI app, or use SwiftUI views in your UIKit app. Both UIKit and SwiftUI provide API to show a view hierarchy of the other. For UIKit to SwiftUI, you would use UIViewControllerRepresentable. For SwiftUI to UIKit, you would use UIHostingController. Landmarks: Interfacing with UIKit walks you through step by step how to implement UIKit in SwiftUI with UIViewControllerRepresentable, and this WWDC22 video demonstrates UIHostingController, for those that want to add SwiftUI to their UIKit. Does Wishlist feature a new iOS 26 font? How can I add custom fonts and text of my app? We’re glad to hear many of you liked wide text shown in Wishlist, however, It is the default system font with some light SwiftUI styling! Check it out for yourself in the sample code when made available, and you can learn more about customizing fonts and text by seeing Font and Applying custom fonts to text. Does Xcode have a dependency graph we can use to optimize our SwiftUI Views? Xcode comes with Instruments. Instruments is the best way to figure out what is causing excessive updates and other issues with performance. That link provides direct tutorials and resources for how to use and understand. Previews also have many useful tools for analyzing SwiftUI views, for more info see Previews in Xcode Check out this video from our latest WWDC Optimize SwiftUI performance with Instruments for information on how to use Instruments to profile and optimize your app with real-world applications If you still have questions, Check out the Instruments section of these forums and create a post so the community has the opportunity to help guide you. Are there UI debugging tools to help diagnose layout issues? Yes, Xcode also features a View Debugger located by selecting the View Debug Hierarchy, pictured below. Use the View Debugger to capture and inspect your view hierarchy, identifying which views affect window sizing. The SwiftUI Inspector also lets you examine view frames and layout behavior. See Diagnosing issues in the appearance of a running app to learn about debugging visual and layout issues. As an absolute beginner, what would be the first go-to step to go for training? Do I need prior knowledge of frameworks to get started with SwiftUI? A great place to learn how to develop for Apple platforms is with Pathways! Many developers start with Develop in Swift tutorials, which exposes you to several frameworks while teaching you the basics of SwiftUI. When you're ready to take your learning further, you can read the documentation for the specific frameworks that interest you at https://developer.apple.com/documentation/.
Topic: UI Frameworks SubTopic: SwiftUI
2
0
119
1w
Button in ToolbarItem is not completely tapable on iOS 26
I have an icon button in toolbar but only the icon is triggering tap events while outside icon button gives tap feedback but event is not firing. Code: ToolbarItem(placement: .navigationBarTrailing) { Button(action: toggleBookmark) { Image(systemName: isBookmarked ? "bookmark.fill" : "bookmark") .resizable() .aspectRatio(0.8, contentMode: .fit) .frame(width: 20, height: 20) } } Here toggleBookmark function is only called if I click on Image but not if I click outside image but on the circular button that appears on iOS 26. See this screen recording.
Topic: UI Frameworks SubTopic: SwiftUI
6
1
163
4h
Swiftui Map Leagal Text is transformed when rotationEffect is applied to Map
I have a problem when applying rotationEffect to a map in in SwiftUI. The legal text in the map is transformed as shown in this image: The following code is part of a much larger and complex view; it is a minimal example to reproduce the error: import SwiftUI import MapKit struct ContentView: View { @State private var offset = CGSize.zero var body: some View { ZStack { let drag = DragGesture() .onChanged { g in offset.width = g.translation.width offset.height = g.translation.height } Map(interactionModes: [.zoom]) .frame(width: 320, height: 220) .rotationEffect(.degrees(Double(offset.width / 12))) .highPriorityGesture(drag) } } } I hope you can help me with this problem.
2
0
54
7h
SwiftUI and undo
In my multiplatform SwiftUI document app, where should I implement undo? In the Views with Forms and Lists, Bindings, data classes or somewhere else? I am now implementing undo in Bindings and Lists, but I'm wondering if that's the right way to do it.
Topic: UI Frameworks SubTopic: SwiftUI
1
0
48
9h
SwiftUI toolbar with IDs crash since macOS 15
I understand this is a known issue, but it’s truly unacceptable that it remains unresolved. Allowing users to customize toolbars is a fundamental macOS feature, and it has been broken since the release of macOS 15. How is it possible that this issue persists even in macOS 15.3 beta (24D5040f)? FB15513599 import SwiftUI struct ContentView: View { @State private var showEditItem = false var body: some View { VStack { VStack { Text("Instructions to reproduce the crash") .font(.title) .padding() Text(""" 1. Click on "Toggle Item" 2. In the menu go to File > New Window 3. In new window, click on "Toggle Item" """) } .padding() Button { showEditItem.toggle() } label: { Text("Toggle Item") } } .padding() .toolbar(id: "main") { ToolbarItem(id: "new") { Button { } label: { Text("New…") } } if showEditItem { ToolbarItem(id: "edit") { Button { } label: { Text("Edit…") } } } } } }
7
3
691
10h
How to stop ios 26 glass effect UI in ios app
Hi everyone, I want to avoid the iOS 26 Liquid Glass effect in my app’s UI. While researching, I found the following possible solution: Steps: Go to Info.plist Add the key: UIDesignRequiresCompatibility Type: Boolean Value: YES I have a few questions about this approach: According to the Apple Developer website, this seems to be a temporary solution. How long will this continue to work, and what would be the recommended long-term solution? Which iOS versions does this support (both older and upcoming versions)? If this method is not recommended, is there another way to disable or avoid the glass effect across the entire app without making major UI changes? Any guidance or suggestions would be greatly appreciated. Thank you!
1
0
90
1d
Liquid Glass Button animating when behind a view when `.interactive()` modifier is applied
When using the .glassEffect modifier on a button in swiftui combined with the .interactive() modifier, the button continues to show the interactive animation even when it’s covered by another element. Example: ZStack { Button { print("Button overlayed by ZStack") // Does not trigger, but interactive animation still plays } label: { image } .glassEffect(.regular.interactive()) Rectangle().fill(.black.opacity(0.7)) } This occurs with overlays, ZStacks, and even if the overlay is a button. Example below: EDIT: It seems like rocketsim's gif recording doesnt show the bug for some reason... really strange... Edit 2: reuploaded gif, recorded as mp4 and converted to gif seems to have worked... Feedback ID: FB22054300 I've attached this sample app to my feedback ticket to help with debugging the issue. It doesn't look like I can share it in this post though.
2
1
108
1d
DynamicViewContent and drop validation (macOS)
If I see it correctly, it is currently not possible to validate a drop operation on a DynamicViewContent when using dropDestination? Just a simple example: Let's say I build a folder view on macOS where I can arrange folders freely. In this case I need to use DynamicViewContent.dropDestination to get an insertion index on drop. However, it seems that methods like dropConfiguration do not have any effect. Als dropDestionation(…, isTargeted:) seems not to be available. Here is my sample code: struct FolderRow: View { let folder: Folder var body: some View { DisclosureGroup(isExpanded: .constant(true)) { ForEach(folder.children) { child in FolderRow(folder: child) } .dropDestination(for: Folder.self) { item, idx in print("Dropped at \(idx)") } } label: { Label(folder.name, systemImage: "folder") .draggable(folder) .dropDestination(for: Folder.self) { items, _ in print("Dropped on Item") } } .dropConfiguration { session in DropConfiguration(operation: .move) } } } struct ContentView: View { @State private var folder: Folder = Folder.sampleData @State private var selection: Set<UUID> = [] var body: some View { NavigationSplitView { List(selection: $selection) { FolderRow(folder: folder) } } detail: { EmptyView() } } } The dropConfiguration is applied on the Label (in this case the "Move" cursor is used instead of the "Copy" cursor). Is there any way to do that or is it just an omission in Swift UI?
0
0
69
1d
SwipeActions-triggered reorder animation briefly removes row and re-inserts it
I’m seeing a visual glitch in SwiftUI List on iOS 26 when row order changes after a swipeActions action. Setup: List + ForEach of items Items are sorted dynamically by isSelected (unselected first, selected last) Swipe action toggles isSelected Row should animate to new position Problem: On swipe select/unselect, the row sometimes appears to disappear briefly, then reappear in the new position Most visible when unselecting an item from the bottom selected group (it should move to top) Sometimes there is a temporary “empty gap” near the top during the move In some row styling setups, row corner masking also looks wrong during animation What I tried: Different animations (default, easeInOut, spring) Adding/removing small dispatch delay before state change Moving section header content outside List Using custom row backgrounds/corners vs system row styling Keeping stable IDs in ForEach Behavior still appears with native List + swipeActions on iOS 26. So my question is: Is this a known issue/regression with List row move animations on iOS 26? Recommended pattern to keep native swipe actions but avoid this visual artifact? This worked smoothly on iOS 18 with the same approach, and the visual glitch appears only after moving to iOS 26.
Topic: UI Frameworks SubTopic: SwiftUI
0
0
84
2d
Data Persistence not functioning upon refresh
Hello, I am attempting to implement a simple button that loads persistent data from a class (see below). Button("Reload Data") { while tableData2.isEmpty == false{ tableData2.remove(at: 0) } while tableView.isEmpty == false{ tableView.remove(at: 0) } //update if csvData.isEmpty == false{ for superRow in csvData[0].tableData2{ tableData2.append(superRow) } for supperRow in csvData[0].tableView{ tableView.append(supperRow) } print("Item at 0: \(csvData[0].tableData2[[0][0]])") print("\(tableData2[0][0])") } else { print("csvData is empty") } } This button DOES work to appropriately print the data stored at the printed location once loaded in initially. The problem is that it doesn’t work across app restarts, which is the whole point of the button. Below I will include the rest of the relevant code with notes: In contentView declaring the persistant variables: Query private var csvData: [csvDataPersist] Environment(\.modelContext) private var modelContext The simple class of data I’m storing/pulling to/from: @Model class csvDataPersist{ var tableView: [[String]] = [] var tableData2: [[String]] = [] init(tableView: [[String]], tableData2: [[String]]) { self.tableView = tableView self.tableData2 = tableData2 } } In (appname)App: I tried both locations of the model container but it didn’t seem to matter var body: some Scene { WindowGroup { ContentView() .modelContainer(for: csvDataPersist.self) } //.modelContainer(for: csvDataPersist.self) .modelContainer(sharedModelContainer) } How I’m attempting to save the data: let newCSVDataPersist = csvDataPersist(tableView: tableView, tableData2: tableData2) //modelContext.rollback() //for superrow in csvData.count{ // csvData[superrow].tableData2.removeAll() //} //modelContext.rollback() //csvData[0].tableData2.removeAll() //csvData[0].tableView.removeAll() if csvData.isEmpty == false { print("not empty, deleting prev data") modelContext.delete(csvData[0]) } else { print("it empty, load data.") } modelContext.insert(newCSVDataPersist) //try modelContext.save() Note that I’ve tried just about every combination of enabling and disabling the commented out lines. This is the part of the code I am the least confident in, but after trying for hours to troubleshoot on my own I would appreciate any input from the community. Something else that may be of note, in a previous attempt, upon a second startup, the terminal would print: "coredata: error: error: persistent history (random number) has to be truncated due to the following entities being removed: ( csvdatapersist )" Why is csvDataPersist getting removed? What is it getting removed by? Looking up this error was fruitless. Most sites instructed me to basically hard reset my simulators, clean the build, restart my computer, and try again. I've done all of these things about a hundred times at this point, with no results. Any help would be much appreciated!
3
0
83
3d
Access Relationship value from deleted model tombstone in SwiftData.
I’m developing an app using SwiftData. In my app, I have two models: User and Address. A user can have multiple addresses. I’m trying to use SwiftData History tracking to implement some logic when addresses are deleted. Specifically, I need to determine which user the address belonged to. From the documentation, I understand that you can preserve attributes from deleted models in a tombstone object using @Attribute(.preserveValueOnDeletion). However, this isn’t working when I try to apply this to a relationship value. Below is a simplified example of my attempts so far. I suspect that simply adding @Attribute(.preserveValueOnDeletion) to a relationship isn’t feasible. If that’s indeed the case, what would be the recommended approach to identify the user associated with an address after it has been deleted? Thank you. @Model class User { var name: String @Relationship(deleteRule: .cascade, inverse: \Address.user) var addresses: [Address] = [] init(name: String) { self.name = name } } @Model class Address { var adress1: String var address2: String var city: String var zip: String @Attribute(.preserveValueOnDeletion) var user: User? init(adress1: String, address2: String, city: String, zip: String) { self.adress1 = adress1 self.address2 = address2 self.city = city self.zip = zip self.user = user } } for transaction in transactions { for change in transaction.changes { switch change { case .delete(let deleted): if let deleted = deleted as? any HistoryDelete<Address> { if let user = deleted.tombstone[\.user] { //this is never executed } } default: break } } }
1
0
74
3d
What is the lifecycle of onReceive subscriptions in SwiftUI views?
I'm trying to better understand how the onReceive modifier behaves in SwiftUI, specifically how its subscription lifecycle relates to view updates. Consider this example: TextField("Name", text: $name) .onReceive(Just(name)) { value in print(value) } This closure runs every time name changes. A common explanation is that SwiftUI recomputes body, which creates a new Just(name) publisher each time. However, this raises some questions for me about how onReceive actually works internally: When SwiftUI recomputes body, is the onReceive modifier recreated and resubscribed? Does SwiftUI automatically cancel the previous subscription when the view updates?
0
0
40
3d
TextKit 2 + SwiftUI (NSViewRepresentable): NSTextLayoutManager rendering attributes don’t reliably draw/update
I’m embedding an NSTextView (TextKit 2) inside a SwiftUI app using NSViewRepresentable. I’m trying to highlight dynamic subranges (changing as the user types) by providing per-range rendering attributes via NSTextLayoutManager’s rendering-attributes mechanism. The issue: the highlight is unreliable. Often, the highlight doesn’t appear at all even though the delegate/data source is returning attributes for the expected range. Sometimes it appears once, but then it stops updating even when the underlying “highlight range” changes. This feels related to SwiftUI - AppKit layout issue when using NSViewRepresentable (as said in https://developer.apple.com/documentation/swiftui/nsviewrepresentable). What I’ve tried Updating the state that drives the highlight range and invalidating layout fragments / asking for relayout Ensuring all updates happen on the main thread. Calling setNeedsDisplay(_:) on the NSViewRepresentable’s underlying view. Toggling the SwiftUI view identity (e.g. .id(...)) to force reconstruction (works, but too expensive / loses state). Question In a SwiftUI + NSViewRepresentable setup with TextKit 2, what is the correct way to make NSTextLayoutManager re-query and redraw rendering attributes when my highlight ranges change? Is there a recommended invalidation call for TextKit 2 to trigger re-rendering of rendering attributes? Or is this a known limitation when hosting NSTextView inside SwiftUI, where rendering attributes aren’t reliably invalidated? If this approach is fragile, is there a better pattern for dynamic highlights that avoids mutating the attributed string (to prevent layout/scroll jitter)?
2
0
145
4d
Crash in SwiftUICore SDFStyle.distanceRange.getter
I've been receiving crash reports about a crash in SDFStyle.distanceRange.getter. I haven't been able to reproduce this, and users haven't given me much information about the circumstances or can't reliably reproduce this either. Googling didn't give any results. I'm happy for any pointers in the right direction. All reports have been on iOS 26 so far. 2026-03-02_23-35-03.7381_+0800-93830d0f537cfb381b42a7e9812953d772adfe64.crash
Topic: UI Frameworks SubTopic: SwiftUI
0
0
109
4d
hapticpatternlibrary.plist error with Text entry fields in Simulator only
When I have a TextField or TextEditor, tapping into it produces these two console entries about 18 times each: CHHapticPattern.mm:487 +[CHHapticPattern patternForKey:error:]: Failed to read pattern library data: Error Domain=NSCocoaErrorDomain Code=260 "The file “hapticpatternlibrary.plist” couldn’t be opened because there is no such file." UserInfo={NSFilePath=/Library/Audio/Tunings/Generic/Haptics/Library/hapticpatternlibrary.plist, NSURL=file:///Library/Audio/Tunings/Generic/Haptics/Library/hapticpatternlibrary.plist, NSUnderlyingError=0x600000ca1b30 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}} <_UIKBFeedbackGenerator: 0x600003505290>: Error creating CHHapticPattern: Error Domain=NSCocoaErrorDomain Code=260 "The file “hapticpatternlibrary.plist” couldn’t be opened because there is no such file." UserInfo={NSFilePath=/Library/Audio/Tunings/Generic/Haptics/Library/hapticpatternlibrary.plist, NSURL=file:///Library/Audio/Tunings/Generic/Haptics/Library/hapticpatternlibrary.plist, NSUnderlyingError=0x600000ca1b30 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}} My app does not use haptics. This doesn't appear to cause any issues, although entering text can feel a bit sluggish (even on device), but I am unable to determine relatedness. None-the-less, it definitely is a lot of log noise. Code to reproduce in simulator (xcode 26.2; ios 26 or 18, with iPhone 16 Pro or iPhone 17 Pro): import SwiftUI struct ContentView: View { @State private var textEntered: String = "" @State private var textEntered2: String = "" @State private var textEntered3: String = "" var body: some View { VStack { Spacer() TextField("Tap Here", text: $textEntered) TextField("Tap Here Too", text: $textEntered2) TextEditor(text: $textEntered3) .overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(.primary, lineWidth: 1)) .frame(height: 100) Spacer() } } } #Preview { ContentView() } Tapping back and forth in these fields generates the errors each time. Thanks, Steve
3
0
490
4d
How do you make a resizable segmented control in SwiftUI for macOS?
In SwiftUI for macOS, how do I configure a Picker as a segmented control to have a flexible width? This design pattern is present in Xcode 26 at the top of the sidebar and inspector panel. I can't figure out the combination of view modifiers to achieve a similar look. import SwiftUI struct ContentView: View { @State private var selection = 0 var body: some View { VStack { Picker("", selection: $selection) { Image(systemName: "doc") Image(systemName: "folder") Image(systemName: "gear") Image(systemName: "globe") .frame(maxWidth: .infinity) // Doesn't do anything. } .labelsHidden() .pickerStyle(.segmented) .frame(maxWidth: .infinity) // Doesn't affect segment sizes. Spacer() } } } I want the entire Picker to fill the width and for each segment to be of equal widths. How? In AppKit I would use AutoLayout for the flexible width and NSSegmentedControl.segmentDistribution for the segment widths. Is there a SwiftUI equivalent? macOS 26 / Xcode 26.3
Topic: UI Frameworks SubTopic: SwiftUI Tags:
0
0
69
5d
SwiftData with shared and private containers
I was hoping for an update of SwiftData which adopted the use of shared and public CloudKit containers, in the same way it does for the private CloudKit container. So firstly, a big request to any Apple devs reading, for this to be a thing! Secondly, what would be a sensible way of adding a shared container in CloudKit to an existing app that is already using SwiftData? Would it be possible to use the new DataStore method to manage CloudKit syncing with a public or shared container?
12
18
3.9k
5d
Detect closing of tab (NSWindowTab) in WindowGroup
I have a SwiftUI app displaying tabbed windows (as NSWindowTab) in a WindowGroup: import SwiftUI @main struct TabTestApp: App { var body: some Scene { WindowGroup{ ContentView() // Hasn't any content of relevance to this question. }.commands{ CommandGroup(after: .newItem) { Button("New Tab") { guard let currentWindow = NSApp.keyWindow, let windowController = currentWindow.windowController else { return } windowController.newWindowForTab(nil) guard let newWindow = NSApp.keyWindow else { return } if currentWindow != newWindow { currentWindow.addTabbedWindow(newWindow, ordered: .above) } }.keyboardShortcut(.init("t", modifiers: [.command])) } } } } Is there a way to detect the closing of one or multiple tabs, e.g. when the user clicks on the tab bar's "Close Other Tabs" option or pushes CMD + W in order to ask the user whether he or she wants to save changes? What I've tried to no avail: Intercept windowWillClose👉Won't be called if a single tab within a window is closed (but only once the last tab of a window is closed). Handling onDissapear()👉Doesn't work since the closing cannot be cancelled. Using DocumentGroup 👉Doesn't work since the app in question isn't about documents (i.e., files which are stored externally), but about data that's stored in a database. Many thanks! Related threads: Preserve all tabs of last window on close. (Like Finder) Detect Close Window vs Close Tab
0
0
47
5d