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
564
2w
Multi-Selection List : changing Binding Array to Binding Set and back again
I am trying to create a menu picker for two or three text items. Small miracles, but I have it basically working. Problem is it uses a set, and I want to pass arrays. I need to modify PickerView so the Bound Parameter is an [String] instead of Set. Have been fighting this for a while now... Hoping for insights. struct PickerView: View { @Binding var colorChoices: Set<String> let defaults = UserDefaults.standard var body: some View { let possibleColors = defaults.object(forKey: "ColorChoices") as? [String] ?? [String]() Menu { ForEach(possibleColors, id: \.self) { item in Button(action: { if colorChoices.contains(item) { colorChoices.remove(item) } else { colorChoices.insert(item) } }) { HStack { Text(item) Spacer() if colorChoices.contains(item) { Image(systemName: "checkmark") } } } } } label: { Label("Select Items", systemImage: "ellipsis.circle") } Text("Selected Colors: \(colorChoices, format: .list(type: .and))") } } #Preview("empty") { @Previewable @State var colorChoices: Set<String> = [] PickerView(colorChoices: $colorChoices) } #Preview("Prefilled") { @Previewable @State var colorChoices: Set<String> = ["Red","Blue"] PickerView(colorChoices: $colorChoices) } My Content View is suppose to set default values the first time it runs, if no values already exist... import SwiftUI struct ContentView: View { @State private var viewDidLoad: Bool = false var body: some View { HomeView() .onAppear { // The following code should execute once the first time contentview loads. If a user navigates back to it, it should not execute a second time. if viewDidLoad == false { viewDidLoad = true // load user defaults let defaults = UserDefaults.standard // set the default list of school colors, unless the user has already updated it prior let defaultColorChoices: [String] = ["Black","Gold","Blue","Red","Green","White"] let colorChoices = defaults.object(forKey: "ColorChoices") as? [String] ?? defaultColorChoices defaults.set(colorChoices, forKey: "ColorChoices") } } } } #Preview { ContentView() } PickLoader allows you to dynamically add or delete choices from the list... import SwiftUI struct PickLoader: View { @State private var newColor: String = "" var body: some View { Form { Section("Active Color Choices") { // we should have set a default color list in contentview, so empty string should not be possible. let defaults = UserDefaults.standard let colorChoices = defaults.object(forKey: "ColorChoices") as? [String] ?? [String]() List { ForEach(colorChoices, id: \.self) { color in Text(color) } .onDelete(perform: delete) HStack { TextField("Add a color", text: $newColor) Button("Add"){ defaults.set(colorChoices + [newColor], forKey: "ColorChoices") newColor = "" } } } } } .navigationTitle("Load Picker") Button("Reset Default Choices") { let defaults = UserDefaults.standard //UserDefaults.standard.removeObject(forKey: "ColorChoices") let colorChoices: [String] = ["Black","Gold","Blue","Red","Green","White"] defaults.set(colorChoices, forKey: "ColorChoices") } Button("Clear all choices") { let defaults = UserDefaults.standard defaults.removeObject(forKey: "ColorChoices") } } } func delete(at offsets: IndexSet) { let defaults = UserDefaults.standard var colorChoices = defaults.object(forKey: "ColorChoices") as? [String] ?? [String]() colorChoices.remove(atOffsets: offsets) defaults.set(colorChoices, forKey: "ColorChoices") } #Preview { PickLoader() } And finally HomeView is where I am testing from - to see if binding works properly... import SwiftUI struct HomeView: View { //@State private var selection: Set<String> = [] //@State private var selection: Set<String> = ["Blue"] @State private var selection: Set<String> = ["Blue", "Red"] var body: some View { NavigationStack { List { Section("Edit Picker") { NavigationLink("Load Picker") { PickLoader() } } Section("Test Picker") { PickerView(colorChoices: $selection) } Section("Current Results") { Text("Current Selection: \(selection, format: .list(type: .and))") } } .navigationBarTitle("Hello, World!") } } } #Preview { HomeView() } If anyone uses this code, there are still issues - buttons on Loader don't update the list on the screen for one, and also dealing with deleting choices that are in use - how does picker deal with them? Probably simply add to the list automatically and move on. If anyone has insights on any of this also, great! but first I just need to understand how to accept an array instead of a set in pickerView. I have tried using a computed value with a get and set, but I can't seem to get it right. Thanks for any assistance! Cheers!
1
0
54
5h
"The compiler is unable to type-check this expression..."
"/Users/rich/Work/IdeaBlitz/IdeaBlitz/IdeaListView.swift:30:25 The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions" Is it just me? I get this on syntax errors, missing commas, missing quotes, and for no particular reason at all that I can see. I don't think I've been able to write a single, simple, SwiftUI view without seeing this multiple times. "Breaking it up" just makes it harder to read. Simple, inline, 2-page views become 8-page, totally unreadable, monstrosities. Am I doing something wrong? Or is this just the state of SwiftUI today? Or is there some way to tell the compiler to take more time on this expression? I mean, if these can be broken up automatically, then why doesn't the compiler to that already?
1
0
66
6h
SwiftData and discarding unsaved changes idea???
Someone smarter than me please tell me if this will work... I want to have an edit screen for a SwiftData class. Auto Save is on, but I want to be able to revert changes. I have read all about sending a copy in, sending an ID and creating a new context without autosave, etc. What about simply creating a second set of ephemeral values in the actual original model. initialize them with the actual fields. Edit them and if you save changes, migrate that back to the permanent fields before returning. Don't have to manage a list of @State variables corresponding to every model field, and don't have to worry about a second model context. Anyone have any idea of the memory / performance implications of doing it this way, and if it is even possible? Does this just make a not quite simple situation even more complicated? Haven't tried yet, just got inspiration from reading some medium content on attributes on my lunch break, and wondering if I am just silly for considering it.
2
0
103
7h
Configurable Watch Widgets "Unable to Load" watchOS 26 Issue
I updated my IntentWidgetProvider recommendations() to return an empty array instead of all my previous static IntentRecommendation to allow my widgets to finally be configurable. When I go to the watch widget chooser I see samples of my widgets OK: But when I touch the sample would should bring up my configurations, I get "Unable to Load": Anybody see this or have any ideas? Thanks.
1
0
34
8h
Cannot get drop action to trigger (Xcode 26 beta 3)
I'm unable to find the right combination modifiers to get drag and drop to work using the new .draggable(containerItemID:) and dragContainer(for:in:selection:_:) modifiers. The drag is initiated with the item's ID, the item is requested from the .dragContainer modifier, but the drop closure is never triggered. Minimal repro: struct Item: Identifiable, Codable, Transferable { var id = UUID() var value: String static var transferRepresentation: some TransferRepresentation { CodableRepresentation(contentType: .tab) } } struct DragDrop: View { @State var items: [Item] = [ Item(value: "Hello"), Item(value: "world"), Item(value: "something"), Item(value: "else") ] var body: some View { List(items) { item in HStack { Text(item.value) Spacer() } .contentShape(Rectangle()) .draggable(containerItemID: item.id) .dropDestination(for: Item.self) { items, session in print("Drop: \(items)") } } .dragContainer(for: Item.self) { itemID in print("Drag: \(itemID)") return items.filter { itemID == $0.id } } } } #Preview("Simple") { DragDrop() }
4
0
65
22h
TabView - .search roles
I'm having some difficulty with a tabview and getting the new search bar to expand from the search icon. The tabview works so far, it looks fine, tapping on the search opens the view I will be modifying to use the search bar. snip from my tabview: var body: some View { TabView(selection: $selectedTab) { Tab("Requests", systemImage: "list.bullet", value: .requests) { OverseerrRequestView(integrationId: integrationId) } Tab("Users", systemImage: "person.3", value: .users) { OverseerrUserView(integrationId: integrationId) } Tab("Search", systemImage: "magnifyingglass", value: .search, role: .search) { NavigationStack { OverseerrView(integrationId: integrationId) .searchable(text: $searchString) } } } .modifier(TabBarMinimizeIfAvailable()) .navigationTitle("Overseerr") .modifier(NavigationBarInlineIfAvailable()) } Currently in that view, I have temporarily constructed a search bar that handles the search function (we're searching externally, not just contents in the view) snip from my view: .safeAreaInset(edge: .bottom) { HStack { Image(systemName: "magnifyingglass") .foregroundColor(.secondary) TextField("Search movies, TV or people", text: $query) .focused($isSearchFieldFocused) .onSubmit { Task { await performSearch() } } .submitLabel(.search) .padding(.vertical, 8) .padding(.horizontal, 4) if !query.isEmpty { Button(action: { query = "" searchResults = [] Task { await loadTrending() } }) { Image(systemName: "xmark.circle.fill") .foregroundColor(.secondary) } } } .padding(.horizontal) .padding(.vertical, 5) .adaptiveGlass() .shadow(radius: 8) .onAppear { isSearchFieldFocused = false } } Notes: .adaptiveGlass() is a modifier I created to easily apply liquid glass or not depending on OS version, so as not to require the use of #if or #available in the views. The end goal here: have the tab view search "tab" open the OverseerrView.swift (Discover) view, activate the animated search bar, and search the input text to the performSearch() function. I have similar needs on other tab views, and am trying to move away from needing to manually create a search bar, when one should work from the .search role. Is there an example project with this search in the tab that I can reference? the landmarks sample project sadly did not include one.
4
0
119
1d
macOS 15.5 destroys SwiftUI Table Performance
Has anyone else noticed that macOS Sequoia 15.5 has a regression in SwiftUI Table scrolling performance? I have complex Tables in a SwiftUI app and they scroll adequately on macOS 15.4.1 but hang, beachball, and stutter while scrolling on macOS 15.5. The exact same build is running in both cases. (I've even reduced the table to three simple columns of text and STILL fail to get entirely smooth scrolling on macOS 15.5.) It's like someone just fundamentally broke Table on macOS. Has anyone else encountered this?
Topic: UI Frameworks SubTopic: SwiftUI
2
0
77
1d
iPadOS 26 Menu Bar Questions
We’re currently working on adding support for a Menu Bar in a cross-platform app built with SwiftUI, aiming to reuse the existing macOS menu bar implementation for iPadOS. The basic functionality is working well, but we’ve run into several challenges due to missing APIs—or ones we may have overlooked. We’d appreciate any insights or suggestions on the following issues: (Xcode 26 beta 3, iPadOS 26 beta 3) Command Handlers (Copy, Cut, Paste, Delete) On iOS/iPadOS, handlers like onCopyCommand, onCutCommand, onPasteCommand, and onDeleteCommand are unavailable. Since we also can’t hide the default context menus, we’re unsure how to properly implement these functions. How can we best support copy/paste behavior on iPadOS using the menu bar? Undo/Redo Support Undo and redo work as expected on macOS, but on iPadOS, the menu items are always grayed out—even though undo/redo functionality is available in the app. Is there a recommended way to enable these items in the menu bar for iPadOS? Hiding Unused Menu Items We’d like to hide system-provided menu items that aren’t relevant to our app, such as: Open… Select All Customize Toolbar… New Window, Show All Windows, Open Windows, etc. Is there a way to control which default items appear in the menu bar? App Settings Menu Is it possible to customize the App Settings menu so it opens our app’s settings view inside the app (similar to a SwiftUI .sheet or navigation push)? Lastly We couldn’t find a comprehensive example that covers most use cases for implementing a custom menu bar on iPadOS using SwiftUI. If there’s an open-source project or documentation that you’ve found helpful, we’d love to see it. Thanks in advance for your help!
Topic: UI Frameworks SubTopic: SwiftUI
1
0
78
1d
Button Touch Not Canceled in ScrollView on Modal in SwiftUI for iOS 18
When displaying a view with a Button inside a ScrollView using the sheet modifier, if you try to close the sheet by swiping and your finger is touching the Button, the touch is not canceled. This issue occurs when building with Xcode 16 but does not occur when building with Xcode 15. Here is screen cast. https://drive.google.com/file/d/1GaOjggWxvjDY38My4JEl-URyik928iBT/view?usp=sharing Code struct ContentView: View { @State var isModalPresented: Bool = false var body: some View { ScrollView { Button { debugPrint("Hello") isModalPresented.toggle() } label: { Text("Hello") .frame(height: 44) } Button { debugPrint("World") } label: { Text("World") .frame(height: 44) } Text("Hoge") .frame(height: 44) .contentShape(Rectangle()) .onTapGesture { debugPrint("Hoge") } } .sheet(isPresented: $isModalPresented) { ContentView() } } }
12
16
2.0k
2d
iOS 26 Beta 3 ScrollPosition object not executing scroll commands while scrollPosition(id:) binding works
I'm implementing a horizontal carousel in iOS 26 Beta 3 using SwiftUI ScrollView with LazyHStack. The goal is to programmatically scroll to a specific card on view load. What I'm trying to do: Display a horizontal carousel of cards using ScrollView + LazyHStack Automatically scroll to the "current" card when the view appears Use iOS 26's new ScrollPosition object for programmatic scrolling Current behavior: The ScrollPosition object receives scroll commands (confirmed via console logs) The scrollTo(id:anchor:) method executes without errors However, the ScrollView does not actually scroll - it remains at position 0 Manual scrolling and scrollTargetBehavior(.viewAligned) work perfectly Code snippet: @State private var scrollPositionObject = ScrollPosition() ScrollView(.horizontal) { LazyHStack(spacing: 16) { ForEach(cards, id: .id) { card in CardView(card: card) .id(card.id) } } .scrollTargetLayout() } .scrollPosition($scrollPositionObject) .scrollTargetBehavior(.viewAligned) .onAppear { let targetId = cards[currentIndex].id DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { scrollPositionObject.scrollTo(id: targetId, anchor: .center) } } Workaround that works: Using the iOS 17 scrollPosition(id:) binding instead of the ScrollPosition object: @State private var scrollPosition: UUID? .scrollPosition(id: $scrollPosition) .onAppear { scrollPosition = cards[currentIndex].id } Environment: iOS 26 Beta 3 Xcode 26 Beta 3 Physical device (iPhone 16 Pro Max) Is this a known issue with ScrollPosition in Beta 3, or am I missing something in the implementation? The older binding approach works fine, but I'd prefer to use the new ScrollPosition API if possible.
Topic: UI Frameworks SubTopic: SwiftUI
0
1
61
2d
Does the canvas view on top of the PDFView not re-render?
I added a canvas view using PDFPageOverlayViewProvider. When I zoom the PDFView, the drawing is scaled, but its quality becomes blurry. How can I fix this? import SwiftUI import PDFKit import PencilKit import CoreGraphics struct ContentView: View { var body: some View { if let url = Bundle.main.url(forResource: "sample", withExtension: "pdf"), let data = try? Data(contentsOf: url), let document = PDFDocument(data: data) { PDFRepresentableView(document: document) } else { Text("fail") } } } #Preview { ContentView() } struct PDFRepresentableView: UIViewRepresentable { let document: PDFDocument let pdfView = PDFView() func makeUIView(context: Context) -> PDFView { pdfView.displayMode = .singlePageContinuous pdfView.usePageViewController(false) pdfView.displayDirection = .vertical pdfView.pageOverlayViewProvider = context.coordinator pdfView.document = document pdfView.autoScales = false pdfView.minScaleFactor = 0.7 pdfView.maxScaleFactor = 4 return pdfView } func updateUIView(_ uiView: PDFView, context: Context) { // Optional: update logic if needed } func makeCoordinator() -> CustomCoordinator { return CustomCoordinator(parent: self) } } class CustomCoordinator: NSObject, PDFPageOverlayViewProvider, PKCanvasViewDelegate { let parent: PDFRepresentableView init(parent: PDFRepresentableView) { self.parent = parent } func pdfView(_ view: PDFView, overlayViewFor page: PDFPage) -> UIView? { let result = UIView() let canvasView = PKCanvasView() canvasView.drawingPolicy = .anyInput canvasView.tool = PKInkingTool(.pen, color: .blue, width: 20) canvasView.translatesAutoresizingMaskIntoConstraints = false result.addSubview(canvasView) NSLayoutConstraint.activate([ canvasView.leadingAnchor.constraint(equalTo: result.leadingAnchor), canvasView.trailingAnchor.constraint(equalTo: result.trailingAnchor), canvasView.topAnchor.constraint(equalTo: result.topAnchor), canvasView.bottomAnchor.constraint(equalTo: result.bottomAnchor) ]) for subView in view.documentView?.subviews ?? [] { subView.isUserInteractionEnabled = true } result.layoutIfNeeded() return result } }
1
0
129
3d
Sheet-like presentation on the side on iPad
Is there a way to get a sheet on the side over an interactive view with a proper glass background on iPad? Ideally, including being able to drag the sheet between medium/large-height sizes (like a sheet with presentationDetents on iPhone), similar to the Maps app: I tried the NavigationSplitView like in the NavigationCookbook example. This is somewhat like it, but it's too narrow (sidebar-like) and doesn't get the full navigation bar: I also played around with .sheet and .presentationDetents and the related modifiers, thinking I could make the sheet appear to the side; but no luck here. It seems to have all the correct behaviors, but it's always presented form-like in the center: Example code for the sheet: import SwiftUI import MapKit struct ContentView: View { var body: some View { Map() .sheet(isPresented: .constant(true)) { NavigationStack { VStack { Text("Hello") NavigationLink("Show Foo") { Text("Foo") .navigationTitle("Foo") .containerBackground(Color.clear, for: .navigation) } } } .presentationDetents([.medium, .large]) .presentationBackgroundInteraction(.enabled) } } } I also tried placing the NavigationStack as an overlay and putting a .glassEffect behind it. From the first sight, this looks okay-ish on beta 3, but seems prone to tricky gotchas and edge cases around the glass effects and related transitions. Seems like not a good approach to me, building such navigational containers myself has been a way too big time-sink for me in the past... Anyway, example code for the overlay approach: import SwiftUI import MapKit struct ContentView: View { var body: some View { Map() .overlay(alignment: .topLeading) { NavigationStack { VStack { Text("Hello") NavigationLink("Show Foo") { ScrollView { VStack { ForEach(1...30, id: \.self) { no in Button("Hello world") {} .buttonStyle(.bordered) } } .frame(maxWidth: .infinity) } .navigationTitle("Foo") .containerBackground(Color.clear, for: .navigation) } } .containerBackground(Color.clear, for: .navigation) } .frame(width: 400) .frame(height: 600) .glassEffect(.regular, in: .rect(cornerRadius: 22)) .padding() } } } Do I miss something here or is this not possible currently with built-in means of the SwiftUI API?
Topic: UI Frameworks SubTopic: SwiftUI
0
0
166
3d
Section Does Not Seem To Expand/Collapse
This is obviously a user error, but I've been working on different possibilities for a couple of days and nothing works. The problem is my Section in the following code doesn't expand or collapse when I click on the chevron: `class AstroCat { var title: String var contents: [ String ] var isExpanded: Bool init(title: String, contents: [String], isExpanded: Bool) { self.title = title self.contents = contents self.isExpanded = isExpanded } } struct TestView: View { @Binding var isShowingTargetSelection: Bool @State var catalog: AstroCat @State private var expanded = false var body: some View { NavigationStack { List { Section(catalog.title, isExpanded: $catalog.isExpanded) { ForEach(catalog.contents, id: \.self) { object in Text(object) } } } .navigationTitle("Target") .listStyle(.sidebar) } } } #Preview { struct TestPreviewContainer : View { @State private var value = false @State var catalog = AstroCat(title: "Solar System", contents: ["Sun", "Mercury", "Venus", "Earth"], isExpanded: true) var body: some View { TestView(isShowingTargetSelection: $value, catalog: catalog) } } return TestPreviewContainer() }` If I change the "isExpanded: $catalog.isExpanded" to just use the local variable "expanded", then it works, so I think I have the basic SwiftUI pieces correct. But using a boolean inside of the class doesn't seem to work (the section just remains expanded or collapsed based on the initial value of the class variable). Any hints? Am I not specifying the binding correctly? (I've tried a bunch of alternatives) Thanks for the help, Robert
2
0
105
3d
View lifecycle in Tabview
In TabView, when I open a view in a Tab, and I switch to another Tab, but the View lifecycle of the view in the old Tab is still not over, and the threads of some functions are still in the background. I want to completely end the View lifecycle of the View in the previously opened tab when switching Tab. How can I do it? Thank you!
0
0
101
4d
Observation feedback loop on simple Map() view declaration
Project minimum iOS deployment is set to 16.4. When running this simple code in console we receive "Observation tracking feedback loop detected!" and map is unusable. Run code: Map(coordinateRegion: .constant(.init())) Console report: ... Observable object key path '\_UICornerProvider.<computed 0x00000001a2768bc0 (Optional<UICoordinateSpace>)>' changed; performing invalidation for [layout] of: <_TtGC7SwiftUI21UIKitPlatformViewHostGVS_P10$1a57c8f9c32PlatformViewRepresentableAdaptorGV15_MapKit_SwiftUI8_MapViewGSaVS2_P10$24ce3fc8014AnnotationData____: 0x10acc2d00; baseClass = _TtGC5UIKit22UICorePlatformViewHostGV7SwiftUIP10$1a57c8f9c32PlatformViewRepresentableAdaptorGV15_MapKit_SwiftUI8_MapViewGSaVS3_P10$24ce3fc8014AnnotationData____; frame = (0 0; 353 595); anchorPoint = (0, 0); tintColor = UIExtendedSRGBColorSpace 0.333333 0.333333 0.333333 1; layer = <CALayer: 0x12443a430>> Observable object key path '\_UICornerProvider.<computed 0x00000001a2768bc0 (Optional<UICoordinateSpace>)>' changed; performing invalidation for [layout] of: <_MapKit_SwiftUI._SwiftUIMKMapView: 0x10ae8ce00; frame = (0 0; 353 595); clipsToBounds = YES; autoresize = W+H; layer = <CALayer: 0x113beb7e0>> Observable object key path '\_UICornerProvider.<computed 0x00000001a2768bc0 (Optional<UICoordinateSpace>)>' changed; performing invalidation for [layout] of: <_MapKit_SwiftUI._SwiftUIMKMapView: 0x10ae8ce00; frame = (0 0; 353 595); clipsToBounds = YES; autoresize = W+H; layer = <CALayer: 0x113beb7e0>> Observable object key path '\_UICornerProvider.<computed 0x00000001a2768bc0 (Optional<UICoordinateSpace>)>' changed; performing invalidation for [layout] of: <_MapKit_SwiftUI._SwiftUIMKMapView: 0x10ae8ce00; frame = (0 0; 353 595); clipsToBounds = YES; autoresize = W+H; layer = <CALayer: 0x113beb7e0>> Observation tracking feedback loop detected! Make a symbolic breakpoint at UIObservationTrackingFeedbackLoopDetected to catch this in the debugger. Refer to the console logs for details about recent invalidations; you can also make a symbolic breakpoint at UIObservationTrackingInvalidated to catch invalidations in the debugger. Object receiving repeated [layout] invalidations: <_TtGC7SwiftUI21UIKitPlatformViewHostGVS_P10$1a57c8f9c32PlatformViewRepresentableAdaptorGV15_MapKit_SwiftUI8_MapViewGSaVS2_P10$24ce3fc8014AnnotationData____: 0x10acc2d00; baseClass = _TtGC5UIKit22UICorePlatformViewHostGV7SwiftUIP10$1a57c8f9c32PlatformViewRepresentableAdaptorGV15_MapKit_SwiftUI8_MapViewGSaVS3_P10$24ce3fc8014AnnotationData____; frame = (0 0; 353 595); anchorPoint = (0, 0); tintColor = UIExtendedSRGBColorSpace 0.333333 0.333333 0.333333 1; layer = <CALayer: 0x12443a430>> Observation tracking feedback loop detected! Make a symbolic breakpoint at UIObservationTrackingFeedbackLoopDetected to catch this in the debugger. Refer to the console logs for details about recent invalidations; you can also make a symbolic breakpoint at UIObservationTrackingInvalidated to catch invalidations in the debugger. Object receiving repeated [layout] invalidations: <_MapKit_SwiftUI._SwiftUIMKMapView: 0x10ae8ce00; frame = (0 0; 353 595); clipsToBounds = YES; autoresize = W+H; layer = <CALayer: 0x113beb7e0>> IDE: Xcode 26 Beta 3 Testing device: iPhone 15 Pro iOS 26 Beta 3 MacOS: Tahoe 26 Beta 3
0
1
48
4d
DeviceActivityReport inside SwiftUI Button doesn’t receive tap gestures (ScreenTime API, iOS 17+)
Hi everyone, I’m experimenting with the new ScreenTime DeviceActivityReport view in SwiftUI (iOS 17 / Xcode 15). My goal is to show the report inside a Button (or, more generally, capture any tap on it) so that I can push a detail screen when the user selects it. Here’s the minimal code that reproduces the issue: import FamilyControls import DeviceActivity import SwiftUI struct ScreenTimeView: View { let center = AuthorizationCenter.shared @State private var context: DeviceActivityReport.Context = .init(rawValue: "Total Activity") @State private var filter = DeviceActivityFilter( segment: .hourly( during: Calendar.current.dateInterval(of: .day, for: .now)! ), users: .all, devices: .init([.iPhone, .iPad]) ) var body: some View { ZStack { DeviceActivityReport(context, filter: filter) } .onAppear { Task { do { try await center.requestAuthorization(for: .individual) } catch { print("Authorization failed:", error) } } } } } struct ContentView: View { var body: some View { ScrollViewReader { _ in ScrollView(showsIndicators: false) { VStack { Button { print("BUTTON TAPPED") // ← never fires } label: { ScreenTimeView() .frame(height: UIScreen.main.bounds.height * 1.4) } } } } } } ** What happens** DeviceActivityReport renders correctly with hourly bars. Tapping anywhere inside the Button does not trigger print("BUTTON TAPPED"). I’ve tried replacing Button with .onTapGesture, adding .contentShape(Rectangle()), and .allowsHitTesting(true), but nothing registers. What I’ve checked Authorisation succeeds—calling code in .onAppear prints no errors. Removing DeviceActivityReport and replacing it with a plain Rectangle() lets the tap gesture fire, so the issue seems specific to DeviceActivityReport.
1
0
91
4d
Implicit list row animations broken in Form container on iOS 26 beta 3
[Submitted as FB18870294, but posting here for visibility.] In iOS 26 beta 3 (23A5287g), implicit animations no longer work when conditionally showing or hiding rows in a Form. Rows with Text or other views inside a Section appear and disappear abruptly, even when wrapped in withAnimation or using .animation() modifiers. This is a regression from iOS 18.5, where the row item animates in and out correctly with the same code. Repro Steps Create a new iOS App › SwiftUI project. Replace its ContentView struct with the code below Build and run on an iOS 18 device. Tap the Show Middle Row toggle and note how the Middle Row animates. Build and run on an iOS 26 beta 3 device. Tap the Show Middle Row toggle. Expected Middle Row item should smoothly animate in and out as it does on iOS 18. Actual Middle Row item appears and disappears abruptly, without any animation. Code struct ContentView: View { @State private var showingMiddleRow = false var body: some View { Form { Section { Toggle( "Show **Middle Row**", isOn: $showingMiddleRow.animation() ) if showingMiddleRow { Text("Middle Row") } Text("Last Row") } } } }
1
3
128
4d