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.

All subtopics
Posts under UI Frameworks topic

Post

Replies

Boosts

Views

Activity

Auxiliary window control in Mac SwiftUI & SwiftData app
I've got a Mac Document App using SwiftUI and SwiftData. All is working well with the models editing, etc. There's a feature I need to implement, and can't seem to make it work. From the main window of the app, I need to be able to launch an auxilliary window containing a view-only representation of the model being edited. The required workflow is something like this: Open a document (SwiftData) Select a sub-model of the document Launch the aux window to display the view of the model data (must be in a separate window, because it will be on a different physical display) Continue making edits to the sub-model, as they are reflected in the other window So, below is the closest I've been able to come, and it's still not working at all. What happens with this code: Click on the "Present" button, the encounter-presentation Window opens, but never loads the data model or the view. It's just an empty window. This is the spot in the main view where the auxiliary window will be launched: @State var presenting: Presentation? = nil var presentingThisEncounter: Bool { presenting?.encounter.id == encounter.id } @Environment(\.openWindow) var openWindow ... if presentingThisEncounter { Button(action: { presenting = nil }) { Label("Stop", systemImage: "stop.fill") .padding(.horizontal, 4) } .preference(key: PresentationPreferenceKey.self, value: presenting) } else { Button(action: { presenting = Presentation(encounter: encounter, display: activeDisplay) openWindow(id: "encounter-presentation") }) { Label("Present", systemImage: "play.fill") .padding(.horizontal, 4) } .preference(key: PresentationPreferenceKey.self, value: nil) } Presentation is declared as: class Presentation: Observable, Equatable { Here's the contents of the App, where the DocumentGroup & model is instantiated, and the aux window is managed: @State var presentation: Presentation? var body: some Scene { DocumentGroup(editing: .encounterList, migrationPlan: EncounterListMigrationPlan.self) { ContentView() .onPreferenceChange(PresentationPreferenceKey.self) { self.presentation = $0 } } Window("Presentation", id: "encounter-presentation") { VStack { if let presentation = presentation { PresentingView(presentation: presentation) } } } } And the definition of PresentationPreferenceKey: struct PresentationPreferenceKey: PreferenceKey { static var defaultValue: Presentation? static func reduce(value: inout Presentation?, nextValue: () -> Presentation?) { value = nextValue() } }
3
0
819
3w
Does @IBSegueAction still not work for AppKit relationship segues from NSWindowController?
I’m working on a storyboard-based AppKit application that uses an NSWindowController containing an NSSplitViewController with multiple child view controllers. The hierarchy is roughly: NSWindowController └── NSSplitViewController ├── NSViewController ├── NSViewController └── NSViewController I am trying to provide dependencies during storyboard instantiation using either @IBSegueAction or instantiateInitialController(creator:), rather than configuring everything after initialisation. What I attempted I added custom initialisers to my view controllers so I can pass dependencies at creation time: class SplitViewController: NSSplitViewController { let dependency: Dependency init?(coder: NSCoder, dependency: Dependency) { self.dependency = dependency super.init(coder: coder) } required init?(coder: NSCoder) { print("init(coder:) was called") fatalError("init(coder:) is not supported") } } I then attempted to intercept storyboard instantiation using @IBSegueAction, trying it in both the window controller and the split view controller: @IBSegueAction func makeSplitViewController(_ coder: NSCoder) -> NSSplitViewController? { SplitViewController(coder: coder, dependency: dependency) } I also tried attaching the segue action at different points in the storyboard, but the behaviour did not change. Observed behaviour Regardless of where I place the segue action, AppKit still appears to call: required init?(coder: NSCoder) This means my custom initialiser is never used for the split view controller or its children. Background reference I found this older known issue in the Xcode 11 release notes: “A Segue Action on a relationship segue between a NSWindowController and a View Controller is currently not supported and ignored. (48252727)” This suggests that, at least historically, AppKit relationship segues ignored segue actions entirely. Has this limitation since been fixed in modern Xcode/macOS SDK releases, or are relationship segues involving NSWindowController still incompatible with @IBSegueAction? More generally, what is the intended way to provide dependencies to an NSSplitViewController and its child view controllers in a storyboard-based AppKit application? I am also unclear whether instantiateInitialController(creator:) participates in the creation of container hierarchies like split view controllers, or only top-level controllers.
2
0
667
3w
SwiftUI Equivalent of Nested Scroll Connection for Collapsing Profile Screens
I'm trying to build a profile-style screen similar to X (Twitter), Instagram, or YouTube. The layout is roughly: ┌──────────────────────────┐ │ Profile Header │ │ Cover image │ │ Avatar │ │ Bio / Stats │ └──────────────────────────┘ ┌──────────────────────────┐ │ Tab Bar │ │ Posts | Media | Likes │ └──────────────────────────┘ ┌──────────────────────────┐ │ Tab Content │ │ │ │ ScrollView / List │ │ OR │ │ Empty State VStack │ │ │ └──────────────────────────┘ Requirements: The profile header should collapse while scrolling up. The tab bar should remain pinned. Once the header is fully collapsed, the active tab's scroll view should start scrolling. While scrolling down, the active tab should scroll back to the top first, then the header should expand. Some tabs may contain: ScrollView + LazyVStack List a non-scrollable VStack (for empty states) The behavior should remain consistent regardless of which tab is active. This feels very similar to Jetpack Compose's NestedScrollConnection, where parent and child scroll containers can cooperatively consume scroll deltas. In SwiftUI, I have explored: ScrollView GeometryReader PreferenceKey Scroll offset tracking Custom UIScrollView wrappers A UIViewControllerRepresentable approach that intercepts pan gestures and coordinates scrolling manually However, I haven't found a SwiftUI-native way for a parent container and child scroll view to negotiate scroll consumption. My questions are: Does SwiftUI provide any equivalent to Compose's NestedScrollConnection? Is there a recommended way to implement this profile-screen pattern purely in SwiftUI? How are people handling cases where some tabs contain scrollable content while other tabs contain only static content? Is bridging to UIKit currently the only practical solution for this kind of coordinated scrolling behavior? Any guidance or examples would be greatly appreciated.
0
0
145
3w
State loss and sheets dismiss on backgrounding app
I've been hitting a weird SwiftUI bug with navigation and state loss and I've managed to reproduce in a very tiny sample project. I've submitted a Feedback FB21681608 but thought it was worth posting here incase any SwiftUI experts can see something obviously wrong. The bug With deeper levels of navigation hierarchy SwiftUI will dismiss views when backgrounding the app. Any work around would be appreciated. This happens in a real app where we have to navigate to a settings screen modally and then a complex flow with other sheets. Sample code Happens in the simulator and on device. import SwiftUI struct ContentView: View { @State private var isPresented = false var body: some View { Button("Show first sheet") { isPresented = true } .sheet(isPresented: $isPresented) { SheetView(count: 1) } } } struct SheetView: View { private enum Path: Hashable { case somePath } @State private var isPresented = false var count: Int var body: some View { NavigationStack { VStack { Text("Sheet \(count)") .font(.largeTitle) // To recreate bug show more than 4 sheets and then switch to the app switcher (CTRL-CMD-Shift-H). // All sheets after number 3 dismiss. Button("Show sheet: \(count + 1)") { isPresented = true } } .sheet(isPresented: $isPresented) { SheetView(count: count + 1) } // Comment out the `navigationDestination` below and the sheets don't dismiss when app goes to the background. // Or move this modifier above the .sheet modifier and the sheets don't dismiss. .navigationDestination(for: Path.self) { _ in fatalError() } } } }
Topic: UI Frameworks SubTopic: SwiftUI
4
3
347
3w
iOS 27 automatic resize
With iOS 27's automatic resizability for iPhone apps on iPad and in iPhone Mirroring, what's the recommended pattern for views that need genuinely different layouts at different size classes — is ViewThatFits the intended tool, or should we still branch on size class for larger structural changes? — Divya Ravi, Senior iOS Engineer
Topic: UI Frameworks SubTopic: SwiftUI
2
2
792
3w
tabViewBottomAccessory in 26.1: View's @State is lost when switching tabs
Any view that is content for the tabViewBottomAccessory API fails to retain its state as of the last couple of 26.1 betas (and RC). The loss of state happens (at least) when the currently selected tab is switched (filed as FB20901325). Here's code to reproduce the issue: struct ContentView: View { @State private var selectedTab = TabSelection.one enum TabSelection: Hashable { case one, two } var body: some View { TabView(selection: $selectedTab) { Tab("One", systemImage: "1.circle", value: .one) { BugExplanationView() } Tab("Two", systemImage: "2.circle", value: .two) { BugExplanationView() } } .tabViewBottomAccessory { AccessoryView() } } } struct AccessoryView: View { @State private var counter = 0 // This guy's state gets lost (as of iOS 26.1) var body: some View { Stepper("Counter: \(counter)", value: $counter) .padding(.horizontal) } } struct BugExplanationView: View { var body: some View { ScrollView { VStack(alignment: .leading, spacing: 16) { Text("(1) Manipulate the counter state") Text("(2) Then switch tabs") Text("BUG: The counter state gets unexpectedly reset!") } .multilineTextAlignment(.leading) } } }
7
4
864
3w
MapKit MapStyle
Does anybody know if I'm missing something here? I'm using .mapStyle(.elevation(.realistic)), which enables the 3D map view, but it causes significant lag when driving in real life, especially at speeds above 50 mph. Everything works perfectly in the Simulator with no issues, but real world performance is much worse. The phone starts heating up almost immediately when driving in this mode through urban areas with 3D map data. Interestingly, the phone does not heat up on motorways, and performance is excellent there. (I guess because there's not so much 3D data to show on motorways) This mode looks fantastic and is one of the most requested features from my users, so I'm trying to figure out how to make it work properly. I've tested both SwiftUI and UIKit implementations and get the same result in both. Also I'm using an iPhone 17 Pro Max and an iPad 11, same result on both, including CarPlay import MapKit import CoreLocation struct ContentView: View { @State private var locationManager = LocationManagerDelegate() @State private var cameraPosition: MapCameraPosition = .userLocation(followsHeading: false, fallback: .automatic) @State private var isTracking: Bool = false var body: some View { Map(position: $cameraPosition) { UserAnnotation() } .mapStyle(.imagery(elevation: .realistic)) .onChange(of: locationManager.location) { _, location in guard isTracking, let location else { return } withAnimation(.linear(duration: 0.5)) { cameraPosition = .camera(MapCamera( centerCoordinate: location.coordinate, distance: 1000, heading: location.course, pitch: 60 )) } } .safeAreaInset(edge: .bottom) { // Added to the safeAreaInset to keep the Apple Logo visible Button("Track") { isTracking.toggle() locationManager.requestPermission() locationManager.startNavigating() } .buttonStyle(.glassProminent) .buttonSizing(.flexible) .controlSize(.extraLarge) .padding(.horizontal) } } } @MainActor @Observable final class LocationManagerDelegate: NSObject, CLLocationManagerDelegate { var location: CLLocation? var authorizationStatus: CLAuthorizationStatus = .notDetermined let manager = CLLocationManager() private var liveUpdateTask: Task<Void, Never>? override init() { super.init() manager.delegate = self manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation manager.allowsBackgroundLocationUpdates = true authorizationStatus = manager.authorizationStatus } func requestPermission() { manager.requestWhenInUseAuthorization() } func startNavigating() { liveUpdateTask = Task { do { for try await update in CLLocationUpdate.liveUpdates(.automotiveNavigation) { guard let newLocation = update.location else { continue } self.location = newLocation } } catch { print("Live updates error: \(error)") } } } func stopNavigating() { liveUpdateTask?.cancel() liveUpdateTask = nil manager.requestLocation() } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { location = locations.last } func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { authorizationStatus = manager.authorizationStatus } } #Preview { ContentView() }
1
0
121
3w
NSTableView: checking for mouse-driven selection changes on macOS 27
I have an NSTableView used as a source list and, alongside it, two editors. When the user selects anything in the table view, its content is opened in the editor that has the focus. When the user Opt-clicks an item in the table, though, the content is opened in the other editor, making it easy for the user to load something in the other editor without having to change the focus first. This has worked for many years using NSTableView.selectiondDidChange / the NSTableViewDelegate as follows: func tableViewSelectionDidChange(_ notification: Notification) { if let event = tableView.window?.currentEvent, event.type == .leftMouseUp || event.type == .leftMouseDown, // (Real app does some other checks here too.) event.modifierFlags.contains(.option) { openInOtherEditor() return } openInCurrentEditor() } However, on macOS 27, it seems that things need to be done differently because of the transition to gesture recognisers for event handling. According to the WWDC video "Modernise Your AppKit App", and to Tech Note TN3212, currentEvent can no longer be relied upon to provide the event that actually triggered an action in NSControl subclasses: The transition to gesture recognizers on NSControl objects changes the timing of when AppKit delivers control action messages with respect to event processing. As a result, currentEvent no longer returns the event that triggered an action. It's unclear whether this new limitation refers only to NSControl.action or to all mouse-driven actions, but from the context and what the rest of the Tech Note has to say, I assume it's the latter. (Especially since you are no longer supposed to override mouseDown(with:), and the Console warns about gestures being disabled if you do override mouseDown(with:) in an NSTableView subclass on macOS 27.) currentEvent still seems to work fine in this situation in the first macOS 27 beta, but it sounds as though we cannot rely on this continuing to be the case. If we should no longer be using currentEvent, then, what should we use instead to determine whether a selection change was triggered by a mouse click? The Tech Note and WWDC video have nothing to say about this. They simply say that instead of overriding mouseDown(with:), you should use the selection-did-change delegate methods, which is of no help here. (By contrast, checking the modifier flags is still straightforward; the Tech Note says to use NSEvent.modifierFlags instead of currentEvent.modifierFlags.) Two solutions sprung to mind, but neither worked: Check tableView.clickedRow != -1 in the selectionDidChange delegate method/notification response. This doesn't work, however, because clickedRow has been reset to -1 by the time NSTableView.selectionDidChange is sent. Add an action to the table view and check clickedRow there. This doesn't work either, though, because although clickedRow is available in the action method, I would now have to load content in response to both an action and a selection change, and since the selection changes before the action is called, there is no way of telling my selection-did-change method not to load in the main editor if Option is held down in the action. The only solution I have found is to override selectRowIndexes(_:byExtendingSelection:), check for clickedRow != -1 there, set a didChangeSelectionWithMouse flag to true if so, and check that in the selection-did-change delegate method. That works, but it's not the most elegant of solutions. So: Am I misunderstanding the Tech Note? Can currentEvent still in fact be used safely in tableViewSelectionDidChange(_:) in macOS 27 and beyond? If not, what is the recommended way of checking that the table selection has been changed by a mouse click? Many thanks!
Topic: UI Frameworks SubTopic: AppKit Tags:
8
0
287
3w
iOS 27 / SwiftUI — Search tab .prominent doesn't morph on activation (field goes to top, tabs don't collapse)
I'm building an app with Xcode 27. I had trouble getting the tab bar to detach the search button onto the trailing side. I found that the search behaviour now works through the new .prominent treatment on iOS 27 (with Tab(role: .search)), and the detached button now displays correctly. My remaining problem is the activation behaviour. Expected (as in the system Phone / News / App Store apps): tapping the search button morphs the tab bar — the other tabs collapse into a single leading button and the search field expands at the bottom, centered. Actual: tapping the search tab pushes the search field to the top of the screen, attached to the navigation bar, with no morph animation and no tab collapse. Setup: Xcode 27.0 beta, iOS 27.0 on a physical iPhone Air Same with the Simulator (by the way... i also have some terrible lag with my app on Simulator + my iPhone even with a release version, but not throught TestFlight... strange...) 3 standard tabs + 1 search tab Single .searchable(text:) applied directly on the TabView (not on the inner NavigationStack) No .introspect or third-party modifiers on the search NavigationStack Is the morph + tab-collapse behaviour automatic for the search tab on iPhone, or does it require an additional modifier/configuration I'm missing? Can anyone confirm whether this morph works on a stable iOS 26 build with equivalent code? I suspect a regression in the 27.0 beta SDK, since the detached button works but the activation morph does not. I'm not yet an expert... so maybe i'm doing something wrong. I'll file Feedback if this is confirmed as a beta bug. Thanks.
Topic: UI Frameworks SubTopic: SwiftUI
1
0
112
3w
Push new views to sidebar when using NavigationPath
I have an existing app that uses NavigationSplitView with a detail view that is never changed and just updates to show changes in data. All navigation changes the sidebar only using NavigationLinks with .isDetailLink(false). Now I'm wanting to use NavigationPath with a simple router and enums. import SwiftUI @main struct NavRouterApp: App { @State private var router = Router() var body: some Scene { WindowGroup { NavigationStack(path: $router.navPath) { ContentView() .navigationDestination(for: AppRoute.self) { route in switch route { case .citizens: ContentView() .environment(router) case .citizen: EmptyView() .environment(router) case .tasform2: TASForm2View() .environment(router) case .start: StartView() .environment(router) case .editcharacteristics: EmptyView() .environment(router) case .basicdata(let citizen): BasicDataView(citizen: citizen) .environment(router) .navigationBarBackButtonHidden(true) case .characteristics: EmptyView() .environment(router) } } } .environment(router) } } } The problem is that pushing a subview now replaces the entire content instead of just the sidebar. Pushing a subview with NavigationSplitView would update the sidebar as desired but I would have to replace the detail view, which is not a good idea. I haven't been able to find any way to accomplish what I want. Suggestions?
Topic: UI Frameworks SubTopic: SwiftUI
6
0
162
3w
IKPictureTaker shows blank panel on macOS 26 — popUpRecentsMenu silently fails with no callback
We're using IKPictureTaker to let users pick a room avatar image. The flow worked correctly on macOS 13–15, but breaks on macOS 26 (Tahoe). Symptoms popUpRecentsMenu(for:withDelegate:didEnd:contextInfo:) — no UI appears at all, and the didEnd selector is never called runModal() — a window appears but its content is completely blank (empty gray rectangle). The app freezes until the user force-quits Minimal reproduction import Quartz let pictureTaker = IKPictureTaker.pictureTaker() pictureTaker?.setCommonValuesForKeys(allowsVideoCapture: true) // Attempt 1 — silent fail, no UI, no callback pictureTaker?.popUpRecentsMenu(for: someButton, withDelegate: self, didEnd: #selector(pictureTakerDidEnd), contextInfo: nil) // Attempt 2 — window appears but content is blank let result = pictureTaker?.runModal() // result is never returned while window is visible; app is frozen Environment macOS 26.0 (Tahoe) — reproducible by QA on multiple machines Xcode 16, Swift 5, deployment target macOS 10.14 Camera permission granted (AVAuthorizationStatus.authorized) App is sandboxed What I've ruled out Camera permission is authorized before the call The view passed to popUpRecentsMenu has a valid, visible, key window Same code works on macOS 13, 14, 15 Question Is this a known regression in macOS 26? Is IKPictureTaker expected to stop working, or is there a required entitlement / initialization step that changed? If the API is effectively unsupported, is NSOpenPanel with allowedContentTypes: [.image] the recommended migration path?
3
0
387
3w
How to override NSTextView dragging behaviour without overriding mouseDown:?
I have an NSTextView subclass that overrides mouseDown: to allow for image resizing. If a user clicks and drags on the edges of an image, I implement custom behaviour that resizes the image (and shows resizing cursors). If the user clicks anywhere else, super's implementation is called. This all works great. As of macOS 27, however, the transition to gesture recognisers instead of overriding mouseDown: means that I should probably be moving away from the above approach. NSTextView now uses the new NSTextSelectionManager to implement selection and dragging via gesture recognisers, although, according to the release notes: Existing NSTextView subclasses that override mouseDown: continue to work through a binary-compatible fallback path. (163365571) It's unclear whether this means that we therefore should still override mouseDown: for custom behaviour in NSTextView, but to me, this, along with the content of Tech Note TN3212, strongly implies that, although it will continue to work thanks to "a binary-compatible fallback", we should entirely move away from overriding mouseDown: in the future. If that is indeed the case, how do we implement custom dragging behaviour--such as for resizing images as in my example--in NSTextView? There still seems to be no way of doing it other than overriding mouseDown:. I had thought that I might be able to add an NSPanGestureRecognizer to the text view and have it fail via its delegate methods if the clicks were outside of an image's edges, but a pan gesture recogniser added to an NSTextView is entirely ignored, presumably because of the private gestures already added. Fortunately everything continues to work for now, but I would like to update my code as much as possible.
Topic: UI Frameworks SubTopic: AppKit Tags:
4
0
245
3w
NSTextView.menuForEvent - getting the affected range on macOS 27
I have an NSTextView subclass that replaces the standard context menu with a custom one by building its own menu in an menuForEvent: override. The context menu that is shown depends on what is selected in the text view, so it checks the current selectedRange to determine which commands should be included. (I could do much the same via the NSTextViewDelegate method textView(_:menu:for:at:), but since my text view subclass is used in several areas, each with their own delegate, it's better to do it in menuForEvent(_:).) This has all worked fine for years, but with NSTextView's transition to gesture recognisers and NSTextSelectionManager for handling text selections in macOS 27, the timings have changed. Previously, if you Ctrl-clicked on a word so that the word is selected and the context menu appears, setSelectedRanges:affinity:stillSelecting: would be called first and then menuForEvent: would be called. On macOS 27, however, the order of events is reversed: menuForEvent: is called first, before setSelectedRanges:affinity:stillSelecting:. (If you implement NSMenuDelegate.menuNeedsUpdate:, that is also called before setSelectedRanges:....) This means that you can no longer rely on selectedRanges in menuForEvent:, because on macOS 27, selectedRanges in menuForEvent: represents the previous selection, not the selection you will actually see on screen when the menu appears. This makes building a custom context menu somewhat tricky. I suspect this is a bug and have reported it as such (FB23251873, with apologies to the engineers for the pleading tone in that report; it was at the end of a long week of getting my head around the gesture recogniser changes. :) ). But it occurs to me that there is nothing in the documentation that guarantees that selectedRanges will be accurate in menuForEvent:; it's just always worked this way. So am I missing something here? Is there a better or more reliable way of getting the range that will be affected by the contextual menu in NSTextView? (The delegate method only provides a single character index, which isn't enough information for spelling corrections and such which require a range.) My current workaround is to rebuild the context menu in setSelectedRanges:affinity:stillSelecting: if it is called between menuForEvent: and didCloseMenu:withEvent:.
Topic: UI Frameworks SubTopic: AppKit Tags:
2
0
186
3w
SwiftUI `OutlineGroup` Should Support Native Reordering with `reorderable` / `reorderContainer`
Description I would like to request native reordering support for SwiftUI hierarchical views, especially OutlineGroup and List(_:children:). In iOS 27, SwiftUI introduces the new reordering APIs: .reorderable() .reorderable(collectionID:) .reorderContainer(for:move:) .reorderContainer(for:in:move:) These APIs work well for flat collections and explicit sectioned collections, but they do not appear to integrate with OutlineGroup, even though OutlineGroup is the natural SwiftUI API for tree-structured data. Currently, OutlineGroup hides the internal recursive ForEach / DisclosureGroup structure, so there is no obvious place to apply reorderable(collectionID:) at each hierarchy level. Current Working Pattern for Sections This works when each parent is represented manually as a section: struct SectionModel: Identifiable { let id: UUID var title: String var items: [Item] } struct Item: Identifiable { let id: UUID var title: String } struct ContentView: View { @State private var sections: [SectionModel] = sampleSections var body: some View { List { ForEach(sections) { section in Section(section.title) { ForEach(section.items) { item in Text(item.title) } .reorderable(collectionID: section.id) } } } .reorderContainer(for: Item.self, in: SectionModel.ID.self) { difference in apply(difference) } } private func apply(_ difference: ReorderDifference<Item.ID, SectionModel.ID>) { // Move item between explicit sections. } } But this does not scale naturally to arbitrary tree data. Desired API Ideally, this should work with OutlineGroup: struct Node: Identifiable { let id: UUID var title: String var children: [Node]? } struct ContentView: View { @State private var nodes: [Node] = sampleTree var body: some View { List { OutlineGroup(nodes, children: \.children) { node in Text(node.title) } .reorderable() } .reorderContainer(for: Node.self) { difference in apply(difference) } } private func apply(_ difference: ReorderDifference<Node.ID, ???>) { // Move node within the tree. } } For hierarchical data, SwiftUI would need to expose the parent or collection identity of the source and destination. For example, something like: .reorderableTree( children: \.children, allowsMoveIntoChildren: true ) Or an overload such as: OutlineGroup(nodes, children: \.children) { node in Text(node.title) } .reorderable(collectionID: \.parentID) With a ReorderDifference that includes: sourceParentID destinationParentID destinationPosition movedItemIDs Why This Matters Many apps represent user-created hierarchical data: folders bookmark collections nested lists project outlines document trees sidebar hierarchies OutlineGroup is the natural SwiftUI abstraction for displaying this data, but reordering currently requires either: 1abandoning OutlineGroup and rebuilding a recursive outline manually; 2flattening the hierarchy into sections, losing the real outline interaction; 3using older manual drag/drop APIs; 4falling back to UIKit/AppKit. None of these approaches feels aligned with SwiftUI's declarative model. Specific Request Please consider adding native reorder support to OutlineGroup and List(_:children:), including support for: moving items within the same parent; moving items between parents; optionally moving an item into another item as a child; preventing invalid moves, such as moving a parent into one of its descendants; exposing source and destination parent identifiers in the move callback; preserving SwiftUI's built-in disclosure UI. Minimal Example of the Current Limitation This is the kind of code I would expect to be possible: List { OutlineGroup(nodes, children: \.children) { node in Text(node.title) } .reorderable() } .reorderContainer(for: Node.self, in: Node.ID.self) { difference in moveNode(using: difference) } But because OutlineGroup creates its recursive rows internally, there is no clear way to attach reorderable(collectionID:) to each parent's child collection. Expected Outcome SwiftUI should provide a first-class way to reorder hierarchical data displayed with OutlineGroup, similar to how flat and sectioned collections can now use reorderable and reorderContainer.
Topic: UI Frameworks SubTopic: SwiftUI
1
1
72
3w
DeviceActivityReport: is host-owned scrolling over an embedded report possible, and can the report present full-screen modals?
I’m building a rich Home surface around a DeviceActivityReport embedded in my host app, and I’ve hit a set of boundaries that I’d like to confirm as intended behavior rather than something I’m doing wrong. All results below are from physical devices running iOS 18 and iOS 26, since Screen Time data is not available in Simulator. What I’m trying to build I want a single scrolling page where: The host app owns some chrome, including a date picker, refresh button, and settings button. The embedded DeviceActivityReport renders the Screen Time data, including totals, a per-hour chart, and per-app usage. The host chrome can react to the report scrolling. Taps inside the report can open a full-screen sheet. Findings so far 1. Report → host App Group writes do not reach the host A UserDefaults(suiteName:) write, or a file written to the App Group container, from inside the report extension returns success. However, the host app reads nil for those keys, including for a plain string marker unrelated to Screen Time data. This appears to be a blanket block across persistence primitives. By contrast, host → report reads work fine: the host writes a value, and the report can read it in makeConfiguration or in the view body. So the channel appears to be one-way: host → report only. 2. A host UIScrollView cannot capture pan gestures that begin over the embedded report I wrapped the DeviceActivityReport in a real UIScrollView, using its own panGestureRecognizer to drive scrolling, not an added recognizer. The report content itself has no internal scrolling. The host scrolls only when the drag begins on a host-owned subview outside the report. A drag beginning over the report does not register with the host at all. No combination of delaysContentTouches, canCancelContentTouches, or direction-locking the pan changes this. This makes it look like the report’s remote view is the touch sink for its own rectangle, and host ancestor gesture recognizers never see touches that begin inside it. 3. A sheet presented from inside the report renders behind host overlays and is bounded by the report container Even when the report is presented edge-to-edge in a fullScreenCover, a .sheet presented from inside the report renders behind a host SwiftUI overlay that is a sibling above it in a ZStack. When the report is embedded inline as a sub-region, a report-presented sheet is bounded to the embed frame rather than the whole screen. Questions 1. Host-owned scrolling Is host-owned vertical scrolling over an embedded DeviceActivityReport supported in any configuration? Is there a sanctioned way to let host gesture recognizers observe or cooperate with touches over the report, or is the report’s rectangle definitively an opaque touch sink by design? 2. Report → host data flow Is the report → host one-way data boundary intended? Is there any supported channel for a report extension to send a value back to the host, other than DeviceActivityEvent thresholds via DeviceActivityMonitor? 3. Screen-sized modal presentation What is the supported way to present a screen-sized modal from a report interaction? Is hosting the report in a full-screen or pushed-navigation context the intended path? If so, are there constraints on what a report-presented modal can cover, such as host chrome or host-owned z-ordering? 4. Intended level of interactivity More broadly, how interactive is a DeviceActivityReport view intended to be? Buttons, @State mutation, DragGesture, and .sheet all work inside the report on device. Is rich interactivity, such as scrolling lists, gesture-driven paging, and in-report overlays, a supported use case? Or is the report intended primarily as a passive presentation surface? Any clarification on which of these are by design versus bugs would help me choose an architecture I can rely on. Environment DeviceActivityReport embedded in host app .individual Family Controls authorization App Group shared between host app and report extension Physical devices only iOS 18 and iOS 26
0
0
82
3w
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:
2
0
237
3w
How do you correctly use a SwiftUI View inside an NSToolbarItem?
I've been struggling to get consistent UI and UX behaviour of SwiftUI Views inside NSToolbarItems and was wondering if there is an official way to use them. I've now revisited this issue in macOS 27 and continue to see some idiosyncrasies. In the attached screenshot, you can see that the highlight area on mouse down between to the two buttons is different. This is the easiest example I've come up with that shows SwiftUI Views exhibiting different behaviour than AppKit Views. Two questions: Is an NSHostingView a valid and supported view type for NSToolbarItem.view? If so, are there any rules that govern how the SwiftUI view should be configured? (ex: frame, sizing options, supported SwiftUI Views, preferred "root view" types, etc?) Sample code that created the two NSToolbarItem buttons in the screenshot. macOS 27 ZY21R0CMGL (Public Beta 1) Xcode 27.0 beta Minimum Deployment target: 27.0 // Left-Top SwiftUI Button (Clipped Highlighting) let item = NSToolbarItem(itemIdentifier: itemIdentifier) let rootView = Button { } label: { Image(systemName: "sidebar.trailing") } item.view = NSHostingView(rootView: rootView) // ... snip .. // Right-Bottom AppKit Button (Correct Highlighting) let item = NSToolbarItem(itemIdentifier: itemIdentifier) item.image = NSImage(systemSymbolName: "sidebar.trailing", accessibilityDescription: nil) Both screenshots are taken on mouse down.
2
0
150
3w
Multiline TextField in a List does not keep the caret visible on iPad
On iPad, a multiline TextField inside a List does not scroll when the text wraps to a new line. The caret and newly entered text can move behind the keyboard until the user scrolls manually. The same code works correctly on iPhone. struct ContentView: View { @State var text = "" var body: some View { List { Color.red.frame(width: 200, height: 500) // When the caret goes to the next line during the text input the scroll doesn't follow it. // So the new text is being overlapped by the keyboard until you scroll manually. TextField( "Run me on iPad and start entering multiline text with keyboard up", text: $text, axis: .vertical ) .lineLimit(1...) Color.red.frame(width: 200, height: 500) } } }
Topic: UI Frameworks SubTopic: SwiftUI
0
0
67
3w
Avoiding crashes in iOS 27 when selected tab is hidden from TabView
I read through the iOS 27 release notes and the following caught my attention: In apps built with the iOS 27.0 and iPadOS 27.0 SDKs, a TabView enforces that its selection is set to a visible tab. TabView might crash when its selection is set to a hidden or otherwise unavailable tab. (164516837) My app has a partially configurable tab bar. If the user currently has tab X selected (in the TabView) and then chooses to hide tab X (by toggling an option in my app's settings), then I guess this could cause a crash. My app already has logic in place so that if the user hides the tab that is currently the selected tab, then the currently selected tab is changed to another one that is always visible. This is handled by an .onChange view modifier (basically: on change of setting, if selected tab is now hidden, change selected tab to something else). However, I'm concerned about the potential for race conditions with this set up. For example, if the TabView re-renders before the selected tab is changed to an available tab, then this could cause a crash. My questions for Apple: Are programmatically configurable TabViews officially supported, or are you recommending against this practice? If they are, what defensive steps are recommended to avoid crashes (e.g. adding a small delay to make sure that the selected tab is changed first before removing a tab from the TabView).
Topic: UI Frameworks SubTopic: SwiftUI
2
0
140
3w
Different keyboards show up for KeyboardType .decimalPad
Environment: iOS 26; iPad Mini/Air/Pro Problem: In a TextField, I am using a keyboard with the type .decimalPad. When I initially tap into the TextField, the "popover" keyboard (i.e. the decimalPad) shows up and focusses the TextField. However, when I click outside the TextField (to dismiss the keyboard), the TextField is still focussed (the keyboard was dismissed though). When reentering in the TextField, another keyboard (from the bottom of the screen) appears (most likely .numeric). Does anybody know how to solve this? What I already tried: I tried listening to the dismissal of the keyboard to manually set the FocusState to nil. However, the dismissal of the "popover/decimal" keyboard is not recognized as such a dismissal. I also tried to build a custom component out of that, but then I lose the TextField behavior, conflicting with HIG.
2
0
280
3w
Auxiliary window control in Mac SwiftUI & SwiftData app
I've got a Mac Document App using SwiftUI and SwiftData. All is working well with the models editing, etc. There's a feature I need to implement, and can't seem to make it work. From the main window of the app, I need to be able to launch an auxilliary window containing a view-only representation of the model being edited. The required workflow is something like this: Open a document (SwiftData) Select a sub-model of the document Launch the aux window to display the view of the model data (must be in a separate window, because it will be on a different physical display) Continue making edits to the sub-model, as they are reflected in the other window So, below is the closest I've been able to come, and it's still not working at all. What happens with this code: Click on the "Present" button, the encounter-presentation Window opens, but never loads the data model or the view. It's just an empty window. This is the spot in the main view where the auxiliary window will be launched: @State var presenting: Presentation? = nil var presentingThisEncounter: Bool { presenting?.encounter.id == encounter.id } @Environment(\.openWindow) var openWindow ... if presentingThisEncounter { Button(action: { presenting = nil }) { Label("Stop", systemImage: "stop.fill") .padding(.horizontal, 4) } .preference(key: PresentationPreferenceKey.self, value: presenting) } else { Button(action: { presenting = Presentation(encounter: encounter, display: activeDisplay) openWindow(id: "encounter-presentation") }) { Label("Present", systemImage: "play.fill") .padding(.horizontal, 4) } .preference(key: PresentationPreferenceKey.self, value: nil) } Presentation is declared as: class Presentation: Observable, Equatable { Here's the contents of the App, where the DocumentGroup & model is instantiated, and the aux window is managed: @State var presentation: Presentation? var body: some Scene { DocumentGroup(editing: .encounterList, migrationPlan: EncounterListMigrationPlan.self) { ContentView() .onPreferenceChange(PresentationPreferenceKey.self) { self.presentation = $0 } } Window("Presentation", id: "encounter-presentation") { VStack { if let presentation = presentation { PresentingView(presentation: presentation) } } } } And the definition of PresentationPreferenceKey: struct PresentationPreferenceKey: PreferenceKey { static var defaultValue: Presentation? static func reduce(value: inout Presentation?, nextValue: () -> Presentation?) { value = nextValue() } }
Replies
3
Boosts
0
Views
819
Activity
3w
Does @IBSegueAction still not work for AppKit relationship segues from NSWindowController?
I’m working on a storyboard-based AppKit application that uses an NSWindowController containing an NSSplitViewController with multiple child view controllers. The hierarchy is roughly: NSWindowController └── NSSplitViewController ├── NSViewController ├── NSViewController └── NSViewController I am trying to provide dependencies during storyboard instantiation using either @IBSegueAction or instantiateInitialController(creator:), rather than configuring everything after initialisation. What I attempted I added custom initialisers to my view controllers so I can pass dependencies at creation time: class SplitViewController: NSSplitViewController { let dependency: Dependency init?(coder: NSCoder, dependency: Dependency) { self.dependency = dependency super.init(coder: coder) } required init?(coder: NSCoder) { print("init(coder:) was called") fatalError("init(coder:) is not supported") } } I then attempted to intercept storyboard instantiation using @IBSegueAction, trying it in both the window controller and the split view controller: @IBSegueAction func makeSplitViewController(_ coder: NSCoder) -> NSSplitViewController? { SplitViewController(coder: coder, dependency: dependency) } I also tried attaching the segue action at different points in the storyboard, but the behaviour did not change. Observed behaviour Regardless of where I place the segue action, AppKit still appears to call: required init?(coder: NSCoder) This means my custom initialiser is never used for the split view controller or its children. Background reference I found this older known issue in the Xcode 11 release notes: “A Segue Action on a relationship segue between a NSWindowController and a View Controller is currently not supported and ignored. (48252727)” This suggests that, at least historically, AppKit relationship segues ignored segue actions entirely. Has this limitation since been fixed in modern Xcode/macOS SDK releases, or are relationship segues involving NSWindowController still incompatible with @IBSegueAction? More generally, what is the intended way to provide dependencies to an NSSplitViewController and its child view controllers in a storyboard-based AppKit application? I am also unclear whether instantiateInitialController(creator:) participates in the creation of container hierarchies like split view controllers, or only top-level controllers.
Replies
2
Boosts
0
Views
667
Activity
3w
SwiftUI Equivalent of Nested Scroll Connection for Collapsing Profile Screens
I'm trying to build a profile-style screen similar to X (Twitter), Instagram, or YouTube. The layout is roughly: ┌──────────────────────────┐ │ Profile Header │ │ Cover image │ │ Avatar │ │ Bio / Stats │ └──────────────────────────┘ ┌──────────────────────────┐ │ Tab Bar │ │ Posts | Media | Likes │ └──────────────────────────┘ ┌──────────────────────────┐ │ Tab Content │ │ │ │ ScrollView / List │ │ OR │ │ Empty State VStack │ │ │ └──────────────────────────┘ Requirements: The profile header should collapse while scrolling up. The tab bar should remain pinned. Once the header is fully collapsed, the active tab's scroll view should start scrolling. While scrolling down, the active tab should scroll back to the top first, then the header should expand. Some tabs may contain: ScrollView + LazyVStack List a non-scrollable VStack (for empty states) The behavior should remain consistent regardless of which tab is active. This feels very similar to Jetpack Compose's NestedScrollConnection, where parent and child scroll containers can cooperatively consume scroll deltas. In SwiftUI, I have explored: ScrollView GeometryReader PreferenceKey Scroll offset tracking Custom UIScrollView wrappers A UIViewControllerRepresentable approach that intercepts pan gestures and coordinates scrolling manually However, I haven't found a SwiftUI-native way for a parent container and child scroll view to negotiate scroll consumption. My questions are: Does SwiftUI provide any equivalent to Compose's NestedScrollConnection? Is there a recommended way to implement this profile-screen pattern purely in SwiftUI? How are people handling cases where some tabs contain scrollable content while other tabs contain only static content? Is bridging to UIKit currently the only practical solution for this kind of coordinated scrolling behavior? Any guidance or examples would be greatly appreciated.
Replies
0
Boosts
0
Views
145
Activity
3w
State loss and sheets dismiss on backgrounding app
I've been hitting a weird SwiftUI bug with navigation and state loss and I've managed to reproduce in a very tiny sample project. I've submitted a Feedback FB21681608 but thought it was worth posting here incase any SwiftUI experts can see something obviously wrong. The bug With deeper levels of navigation hierarchy SwiftUI will dismiss views when backgrounding the app. Any work around would be appreciated. This happens in a real app where we have to navigate to a settings screen modally and then a complex flow with other sheets. Sample code Happens in the simulator and on device. import SwiftUI struct ContentView: View { @State private var isPresented = false var body: some View { Button("Show first sheet") { isPresented = true } .sheet(isPresented: $isPresented) { SheetView(count: 1) } } } struct SheetView: View { private enum Path: Hashable { case somePath } @State private var isPresented = false var count: Int var body: some View { NavigationStack { VStack { Text("Sheet \(count)") .font(.largeTitle) // To recreate bug show more than 4 sheets and then switch to the app switcher (CTRL-CMD-Shift-H). // All sheets after number 3 dismiss. Button("Show sheet: \(count + 1)") { isPresented = true } } .sheet(isPresented: $isPresented) { SheetView(count: count + 1) } // Comment out the `navigationDestination` below and the sheets don't dismiss when app goes to the background. // Or move this modifier above the .sheet modifier and the sheets don't dismiss. .navigationDestination(for: Path.self) { _ in fatalError() } } } }
Topic: UI Frameworks SubTopic: SwiftUI
Replies
4
Boosts
3
Views
347
Activity
3w
iOS 27 automatic resize
With iOS 27's automatic resizability for iPhone apps on iPad and in iPhone Mirroring, what's the recommended pattern for views that need genuinely different layouts at different size classes — is ViewThatFits the intended tool, or should we still branch on size class for larger structural changes? — Divya Ravi, Senior iOS Engineer
Topic: UI Frameworks SubTopic: SwiftUI
Replies
2
Boosts
2
Views
792
Activity
3w
tabViewBottomAccessory in 26.1: View's @State is lost when switching tabs
Any view that is content for the tabViewBottomAccessory API fails to retain its state as of the last couple of 26.1 betas (and RC). The loss of state happens (at least) when the currently selected tab is switched (filed as FB20901325). Here's code to reproduce the issue: struct ContentView: View { @State private var selectedTab = TabSelection.one enum TabSelection: Hashable { case one, two } var body: some View { TabView(selection: $selectedTab) { Tab("One", systemImage: "1.circle", value: .one) { BugExplanationView() } Tab("Two", systemImage: "2.circle", value: .two) { BugExplanationView() } } .tabViewBottomAccessory { AccessoryView() } } } struct AccessoryView: View { @State private var counter = 0 // This guy's state gets lost (as of iOS 26.1) var body: some View { Stepper("Counter: \(counter)", value: $counter) .padding(.horizontal) } } struct BugExplanationView: View { var body: some View { ScrollView { VStack(alignment: .leading, spacing: 16) { Text("(1) Manipulate the counter state") Text("(2) Then switch tabs") Text("BUG: The counter state gets unexpectedly reset!") } .multilineTextAlignment(.leading) } } }
Replies
7
Boosts
4
Views
864
Activity
3w
MapKit MapStyle
Does anybody know if I'm missing something here? I'm using .mapStyle(.elevation(.realistic)), which enables the 3D map view, but it causes significant lag when driving in real life, especially at speeds above 50 mph. Everything works perfectly in the Simulator with no issues, but real world performance is much worse. The phone starts heating up almost immediately when driving in this mode through urban areas with 3D map data. Interestingly, the phone does not heat up on motorways, and performance is excellent there. (I guess because there's not so much 3D data to show on motorways) This mode looks fantastic and is one of the most requested features from my users, so I'm trying to figure out how to make it work properly. I've tested both SwiftUI and UIKit implementations and get the same result in both. Also I'm using an iPhone 17 Pro Max and an iPad 11, same result on both, including CarPlay import MapKit import CoreLocation struct ContentView: View { @State private var locationManager = LocationManagerDelegate() @State private var cameraPosition: MapCameraPosition = .userLocation(followsHeading: false, fallback: .automatic) @State private var isTracking: Bool = false var body: some View { Map(position: $cameraPosition) { UserAnnotation() } .mapStyle(.imagery(elevation: .realistic)) .onChange(of: locationManager.location) { _, location in guard isTracking, let location else { return } withAnimation(.linear(duration: 0.5)) { cameraPosition = .camera(MapCamera( centerCoordinate: location.coordinate, distance: 1000, heading: location.course, pitch: 60 )) } } .safeAreaInset(edge: .bottom) { // Added to the safeAreaInset to keep the Apple Logo visible Button("Track") { isTracking.toggle() locationManager.requestPermission() locationManager.startNavigating() } .buttonStyle(.glassProminent) .buttonSizing(.flexible) .controlSize(.extraLarge) .padding(.horizontal) } } } @MainActor @Observable final class LocationManagerDelegate: NSObject, CLLocationManagerDelegate { var location: CLLocation? var authorizationStatus: CLAuthorizationStatus = .notDetermined let manager = CLLocationManager() private var liveUpdateTask: Task<Void, Never>? override init() { super.init() manager.delegate = self manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation manager.allowsBackgroundLocationUpdates = true authorizationStatus = manager.authorizationStatus } func requestPermission() { manager.requestWhenInUseAuthorization() } func startNavigating() { liveUpdateTask = Task { do { for try await update in CLLocationUpdate.liveUpdates(.automotiveNavigation) { guard let newLocation = update.location else { continue } self.location = newLocation } } catch { print("Live updates error: \(error)") } } } func stopNavigating() { liveUpdateTask?.cancel() liveUpdateTask = nil manager.requestLocation() } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { location = locations.last } func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { authorizationStatus = manager.authorizationStatus } } #Preview { ContentView() }
Replies
1
Boosts
0
Views
121
Activity
3w
NSTableView: checking for mouse-driven selection changes on macOS 27
I have an NSTableView used as a source list and, alongside it, two editors. When the user selects anything in the table view, its content is opened in the editor that has the focus. When the user Opt-clicks an item in the table, though, the content is opened in the other editor, making it easy for the user to load something in the other editor without having to change the focus first. This has worked for many years using NSTableView.selectiondDidChange / the NSTableViewDelegate as follows: func tableViewSelectionDidChange(_ notification: Notification) { if let event = tableView.window?.currentEvent, event.type == .leftMouseUp || event.type == .leftMouseDown, // (Real app does some other checks here too.) event.modifierFlags.contains(.option) { openInOtherEditor() return } openInCurrentEditor() } However, on macOS 27, it seems that things need to be done differently because of the transition to gesture recognisers for event handling. According to the WWDC video "Modernise Your AppKit App", and to Tech Note TN3212, currentEvent can no longer be relied upon to provide the event that actually triggered an action in NSControl subclasses: The transition to gesture recognizers on NSControl objects changes the timing of when AppKit delivers control action messages with respect to event processing. As a result, currentEvent no longer returns the event that triggered an action. It's unclear whether this new limitation refers only to NSControl.action or to all mouse-driven actions, but from the context and what the rest of the Tech Note has to say, I assume it's the latter. (Especially since you are no longer supposed to override mouseDown(with:), and the Console warns about gestures being disabled if you do override mouseDown(with:) in an NSTableView subclass on macOS 27.) currentEvent still seems to work fine in this situation in the first macOS 27 beta, but it sounds as though we cannot rely on this continuing to be the case. If we should no longer be using currentEvent, then, what should we use instead to determine whether a selection change was triggered by a mouse click? The Tech Note and WWDC video have nothing to say about this. They simply say that instead of overriding mouseDown(with:), you should use the selection-did-change delegate methods, which is of no help here. (By contrast, checking the modifier flags is still straightforward; the Tech Note says to use NSEvent.modifierFlags instead of currentEvent.modifierFlags.) Two solutions sprung to mind, but neither worked: Check tableView.clickedRow != -1 in the selectionDidChange delegate method/notification response. This doesn't work, however, because clickedRow has been reset to -1 by the time NSTableView.selectionDidChange is sent. Add an action to the table view and check clickedRow there. This doesn't work either, though, because although clickedRow is available in the action method, I would now have to load content in response to both an action and a selection change, and since the selection changes before the action is called, there is no way of telling my selection-did-change method not to load in the main editor if Option is held down in the action. The only solution I have found is to override selectRowIndexes(_:byExtendingSelection:), check for clickedRow != -1 there, set a didChangeSelectionWithMouse flag to true if so, and check that in the selection-did-change delegate method. That works, but it's not the most elegant of solutions. So: Am I misunderstanding the Tech Note? Can currentEvent still in fact be used safely in tableViewSelectionDidChange(_:) in macOS 27 and beyond? If not, what is the recommended way of checking that the table selection has been changed by a mouse click? Many thanks!
Topic: UI Frameworks SubTopic: AppKit Tags:
Replies
8
Boosts
0
Views
287
Activity
3w
iOS 27 / SwiftUI — Search tab .prominent doesn't morph on activation (field goes to top, tabs don't collapse)
I'm building an app with Xcode 27. I had trouble getting the tab bar to detach the search button onto the trailing side. I found that the search behaviour now works through the new .prominent treatment on iOS 27 (with Tab(role: .search)), and the detached button now displays correctly. My remaining problem is the activation behaviour. Expected (as in the system Phone / News / App Store apps): tapping the search button morphs the tab bar — the other tabs collapse into a single leading button and the search field expands at the bottom, centered. Actual: tapping the search tab pushes the search field to the top of the screen, attached to the navigation bar, with no morph animation and no tab collapse. Setup: Xcode 27.0 beta, iOS 27.0 on a physical iPhone Air Same with the Simulator (by the way... i also have some terrible lag with my app on Simulator + my iPhone even with a release version, but not throught TestFlight... strange...) 3 standard tabs + 1 search tab Single .searchable(text:) applied directly on the TabView (not on the inner NavigationStack) No .introspect or third-party modifiers on the search NavigationStack Is the morph + tab-collapse behaviour automatic for the search tab on iPhone, or does it require an additional modifier/configuration I'm missing? Can anyone confirm whether this morph works on a stable iOS 26 build with equivalent code? I suspect a regression in the 27.0 beta SDK, since the detached button works but the activation morph does not. I'm not yet an expert... so maybe i'm doing something wrong. I'll file Feedback if this is confirmed as a beta bug. Thanks.
Topic: UI Frameworks SubTopic: SwiftUI
Replies
1
Boosts
0
Views
112
Activity
3w
Push new views to sidebar when using NavigationPath
I have an existing app that uses NavigationSplitView with a detail view that is never changed and just updates to show changes in data. All navigation changes the sidebar only using NavigationLinks with .isDetailLink(false). Now I'm wanting to use NavigationPath with a simple router and enums. import SwiftUI @main struct NavRouterApp: App { @State private var router = Router() var body: some Scene { WindowGroup { NavigationStack(path: $router.navPath) { ContentView() .navigationDestination(for: AppRoute.self) { route in switch route { case .citizens: ContentView() .environment(router) case .citizen: EmptyView() .environment(router) case .tasform2: TASForm2View() .environment(router) case .start: StartView() .environment(router) case .editcharacteristics: EmptyView() .environment(router) case .basicdata(let citizen): BasicDataView(citizen: citizen) .environment(router) .navigationBarBackButtonHidden(true) case .characteristics: EmptyView() .environment(router) } } } .environment(router) } } } The problem is that pushing a subview now replaces the entire content instead of just the sidebar. Pushing a subview with NavigationSplitView would update the sidebar as desired but I would have to replace the detail view, which is not a good idea. I haven't been able to find any way to accomplish what I want. Suggestions?
Topic: UI Frameworks SubTopic: SwiftUI
Replies
6
Boosts
0
Views
162
Activity
3w
IKPictureTaker shows blank panel on macOS 26 — popUpRecentsMenu silently fails with no callback
We're using IKPictureTaker to let users pick a room avatar image. The flow worked correctly on macOS 13–15, but breaks on macOS 26 (Tahoe). Symptoms popUpRecentsMenu(for:withDelegate:didEnd:contextInfo:) — no UI appears at all, and the didEnd selector is never called runModal() — a window appears but its content is completely blank (empty gray rectangle). The app freezes until the user force-quits Minimal reproduction import Quartz let pictureTaker = IKPictureTaker.pictureTaker() pictureTaker?.setCommonValuesForKeys(allowsVideoCapture: true) // Attempt 1 — silent fail, no UI, no callback pictureTaker?.popUpRecentsMenu(for: someButton, withDelegate: self, didEnd: #selector(pictureTakerDidEnd), contextInfo: nil) // Attempt 2 — window appears but content is blank let result = pictureTaker?.runModal() // result is never returned while window is visible; app is frozen Environment macOS 26.0 (Tahoe) — reproducible by QA on multiple machines Xcode 16, Swift 5, deployment target macOS 10.14 Camera permission granted (AVAuthorizationStatus.authorized) App is sandboxed What I've ruled out Camera permission is authorized before the call The view passed to popUpRecentsMenu has a valid, visible, key window Same code works on macOS 13, 14, 15 Question Is this a known regression in macOS 26? Is IKPictureTaker expected to stop working, or is there a required entitlement / initialization step that changed? If the API is effectively unsupported, is NSOpenPanel with allowedContentTypes: [.image] the recommended migration path?
Replies
3
Boosts
0
Views
387
Activity
3w
How to override NSTextView dragging behaviour without overriding mouseDown:?
I have an NSTextView subclass that overrides mouseDown: to allow for image resizing. If a user clicks and drags on the edges of an image, I implement custom behaviour that resizes the image (and shows resizing cursors). If the user clicks anywhere else, super's implementation is called. This all works great. As of macOS 27, however, the transition to gesture recognisers instead of overriding mouseDown: means that I should probably be moving away from the above approach. NSTextView now uses the new NSTextSelectionManager to implement selection and dragging via gesture recognisers, although, according to the release notes: Existing NSTextView subclasses that override mouseDown: continue to work through a binary-compatible fallback path. (163365571) It's unclear whether this means that we therefore should still override mouseDown: for custom behaviour in NSTextView, but to me, this, along with the content of Tech Note TN3212, strongly implies that, although it will continue to work thanks to "a binary-compatible fallback", we should entirely move away from overriding mouseDown: in the future. If that is indeed the case, how do we implement custom dragging behaviour--such as for resizing images as in my example--in NSTextView? There still seems to be no way of doing it other than overriding mouseDown:. I had thought that I might be able to add an NSPanGestureRecognizer to the text view and have it fail via its delegate methods if the clicks were outside of an image's edges, but a pan gesture recogniser added to an NSTextView is entirely ignored, presumably because of the private gestures already added. Fortunately everything continues to work for now, but I would like to update my code as much as possible.
Topic: UI Frameworks SubTopic: AppKit Tags:
Replies
4
Boosts
0
Views
245
Activity
3w
NSTextView.menuForEvent - getting the affected range on macOS 27
I have an NSTextView subclass that replaces the standard context menu with a custom one by building its own menu in an menuForEvent: override. The context menu that is shown depends on what is selected in the text view, so it checks the current selectedRange to determine which commands should be included. (I could do much the same via the NSTextViewDelegate method textView(_:menu:for:at:), but since my text view subclass is used in several areas, each with their own delegate, it's better to do it in menuForEvent(_:).) This has all worked fine for years, but with NSTextView's transition to gesture recognisers and NSTextSelectionManager for handling text selections in macOS 27, the timings have changed. Previously, if you Ctrl-clicked on a word so that the word is selected and the context menu appears, setSelectedRanges:affinity:stillSelecting: would be called first and then menuForEvent: would be called. On macOS 27, however, the order of events is reversed: menuForEvent: is called first, before setSelectedRanges:affinity:stillSelecting:. (If you implement NSMenuDelegate.menuNeedsUpdate:, that is also called before setSelectedRanges:....) This means that you can no longer rely on selectedRanges in menuForEvent:, because on macOS 27, selectedRanges in menuForEvent: represents the previous selection, not the selection you will actually see on screen when the menu appears. This makes building a custom context menu somewhat tricky. I suspect this is a bug and have reported it as such (FB23251873, with apologies to the engineers for the pleading tone in that report; it was at the end of a long week of getting my head around the gesture recogniser changes. :) ). But it occurs to me that there is nothing in the documentation that guarantees that selectedRanges will be accurate in menuForEvent:; it's just always worked this way. So am I missing something here? Is there a better or more reliable way of getting the range that will be affected by the contextual menu in NSTextView? (The delegate method only provides a single character index, which isn't enough information for spelling corrections and such which require a range.) My current workaround is to rebuild the context menu in setSelectedRanges:affinity:stillSelecting: if it is called between menuForEvent: and didCloseMenu:withEvent:.
Topic: UI Frameworks SubTopic: AppKit Tags:
Replies
2
Boosts
0
Views
186
Activity
3w
SwiftUI `OutlineGroup` Should Support Native Reordering with `reorderable` / `reorderContainer`
Description I would like to request native reordering support for SwiftUI hierarchical views, especially OutlineGroup and List(_:children:). In iOS 27, SwiftUI introduces the new reordering APIs: .reorderable() .reorderable(collectionID:) .reorderContainer(for:move:) .reorderContainer(for:in:move:) These APIs work well for flat collections and explicit sectioned collections, but they do not appear to integrate with OutlineGroup, even though OutlineGroup is the natural SwiftUI API for tree-structured data. Currently, OutlineGroup hides the internal recursive ForEach / DisclosureGroup structure, so there is no obvious place to apply reorderable(collectionID:) at each hierarchy level. Current Working Pattern for Sections This works when each parent is represented manually as a section: struct SectionModel: Identifiable { let id: UUID var title: String var items: [Item] } struct Item: Identifiable { let id: UUID var title: String } struct ContentView: View { @State private var sections: [SectionModel] = sampleSections var body: some View { List { ForEach(sections) { section in Section(section.title) { ForEach(section.items) { item in Text(item.title) } .reorderable(collectionID: section.id) } } } .reorderContainer(for: Item.self, in: SectionModel.ID.self) { difference in apply(difference) } } private func apply(_ difference: ReorderDifference<Item.ID, SectionModel.ID>) { // Move item between explicit sections. } } But this does not scale naturally to arbitrary tree data. Desired API Ideally, this should work with OutlineGroup: struct Node: Identifiable { let id: UUID var title: String var children: [Node]? } struct ContentView: View { @State private var nodes: [Node] = sampleTree var body: some View { List { OutlineGroup(nodes, children: \.children) { node in Text(node.title) } .reorderable() } .reorderContainer(for: Node.self) { difference in apply(difference) } } private func apply(_ difference: ReorderDifference<Node.ID, ???>) { // Move node within the tree. } } For hierarchical data, SwiftUI would need to expose the parent or collection identity of the source and destination. For example, something like: .reorderableTree( children: \.children, allowsMoveIntoChildren: true ) Or an overload such as: OutlineGroup(nodes, children: \.children) { node in Text(node.title) } .reorderable(collectionID: \.parentID) With a ReorderDifference that includes: sourceParentID destinationParentID destinationPosition movedItemIDs Why This Matters Many apps represent user-created hierarchical data: folders bookmark collections nested lists project outlines document trees sidebar hierarchies OutlineGroup is the natural SwiftUI abstraction for displaying this data, but reordering currently requires either: 1abandoning OutlineGroup and rebuilding a recursive outline manually; 2flattening the hierarchy into sections, losing the real outline interaction; 3using older manual drag/drop APIs; 4falling back to UIKit/AppKit. None of these approaches feels aligned with SwiftUI's declarative model. Specific Request Please consider adding native reorder support to OutlineGroup and List(_:children:), including support for: moving items within the same parent; moving items between parents; optionally moving an item into another item as a child; preventing invalid moves, such as moving a parent into one of its descendants; exposing source and destination parent identifiers in the move callback; preserving SwiftUI's built-in disclosure UI. Minimal Example of the Current Limitation This is the kind of code I would expect to be possible: List { OutlineGroup(nodes, children: \.children) { node in Text(node.title) } .reorderable() } .reorderContainer(for: Node.self, in: Node.ID.self) { difference in moveNode(using: difference) } But because OutlineGroup creates its recursive rows internally, there is no clear way to attach reorderable(collectionID:) to each parent's child collection. Expected Outcome SwiftUI should provide a first-class way to reorder hierarchical data displayed with OutlineGroup, similar to how flat and sectioned collections can now use reorderable and reorderContainer.
Topic: UI Frameworks SubTopic: SwiftUI
Replies
1
Boosts
1
Views
72
Activity
3w
DeviceActivityReport: is host-owned scrolling over an embedded report possible, and can the report present full-screen modals?
I’m building a rich Home surface around a DeviceActivityReport embedded in my host app, and I’ve hit a set of boundaries that I’d like to confirm as intended behavior rather than something I’m doing wrong. All results below are from physical devices running iOS 18 and iOS 26, since Screen Time data is not available in Simulator. What I’m trying to build I want a single scrolling page where: The host app owns some chrome, including a date picker, refresh button, and settings button. The embedded DeviceActivityReport renders the Screen Time data, including totals, a per-hour chart, and per-app usage. The host chrome can react to the report scrolling. Taps inside the report can open a full-screen sheet. Findings so far 1. Report → host App Group writes do not reach the host A UserDefaults(suiteName:) write, or a file written to the App Group container, from inside the report extension returns success. However, the host app reads nil for those keys, including for a plain string marker unrelated to Screen Time data. This appears to be a blanket block across persistence primitives. By contrast, host → report reads work fine: the host writes a value, and the report can read it in makeConfiguration or in the view body. So the channel appears to be one-way: host → report only. 2. A host UIScrollView cannot capture pan gestures that begin over the embedded report I wrapped the DeviceActivityReport in a real UIScrollView, using its own panGestureRecognizer to drive scrolling, not an added recognizer. The report content itself has no internal scrolling. The host scrolls only when the drag begins on a host-owned subview outside the report. A drag beginning over the report does not register with the host at all. No combination of delaysContentTouches, canCancelContentTouches, or direction-locking the pan changes this. This makes it look like the report’s remote view is the touch sink for its own rectangle, and host ancestor gesture recognizers never see touches that begin inside it. 3. A sheet presented from inside the report renders behind host overlays and is bounded by the report container Even when the report is presented edge-to-edge in a fullScreenCover, a .sheet presented from inside the report renders behind a host SwiftUI overlay that is a sibling above it in a ZStack. When the report is embedded inline as a sub-region, a report-presented sheet is bounded to the embed frame rather than the whole screen. Questions 1. Host-owned scrolling Is host-owned vertical scrolling over an embedded DeviceActivityReport supported in any configuration? Is there a sanctioned way to let host gesture recognizers observe or cooperate with touches over the report, or is the report’s rectangle definitively an opaque touch sink by design? 2. Report → host data flow Is the report → host one-way data boundary intended? Is there any supported channel for a report extension to send a value back to the host, other than DeviceActivityEvent thresholds via DeviceActivityMonitor? 3. Screen-sized modal presentation What is the supported way to present a screen-sized modal from a report interaction? Is hosting the report in a full-screen or pushed-navigation context the intended path? If so, are there constraints on what a report-presented modal can cover, such as host chrome or host-owned z-ordering? 4. Intended level of interactivity More broadly, how interactive is a DeviceActivityReport view intended to be? Buttons, @State mutation, DragGesture, and .sheet all work inside the report on device. Is rich interactivity, such as scrolling lists, gesture-driven paging, and in-report overlays, a supported use case? Or is the report intended primarily as a passive presentation surface? Any clarification on which of these are by design versus bugs would help me choose an architecture I can rely on. Environment DeviceActivityReport embedded in host app .individual Family Controls authorization App Group shared between host app and report extension Physical devices only iOS 18 and iOS 26
Replies
0
Boosts
0
Views
82
Activity
3w
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:
Replies
2
Boosts
0
Views
237
Activity
3w
How do you correctly use a SwiftUI View inside an NSToolbarItem?
I've been struggling to get consistent UI and UX behaviour of SwiftUI Views inside NSToolbarItems and was wondering if there is an official way to use them. I've now revisited this issue in macOS 27 and continue to see some idiosyncrasies. In the attached screenshot, you can see that the highlight area on mouse down between to the two buttons is different. This is the easiest example I've come up with that shows SwiftUI Views exhibiting different behaviour than AppKit Views. Two questions: Is an NSHostingView a valid and supported view type for NSToolbarItem.view? If so, are there any rules that govern how the SwiftUI view should be configured? (ex: frame, sizing options, supported SwiftUI Views, preferred "root view" types, etc?) Sample code that created the two NSToolbarItem buttons in the screenshot. macOS 27 ZY21R0CMGL (Public Beta 1) Xcode 27.0 beta Minimum Deployment target: 27.0 // Left-Top SwiftUI Button (Clipped Highlighting) let item = NSToolbarItem(itemIdentifier: itemIdentifier) let rootView = Button { } label: { Image(systemName: "sidebar.trailing") } item.view = NSHostingView(rootView: rootView) // ... snip .. // Right-Bottom AppKit Button (Correct Highlighting) let item = NSToolbarItem(itemIdentifier: itemIdentifier) item.image = NSImage(systemSymbolName: "sidebar.trailing", accessibilityDescription: nil) Both screenshots are taken on mouse down.
Replies
2
Boosts
0
Views
150
Activity
3w
Multiline TextField in a List does not keep the caret visible on iPad
On iPad, a multiline TextField inside a List does not scroll when the text wraps to a new line. The caret and newly entered text can move behind the keyboard until the user scrolls manually. The same code works correctly on iPhone. struct ContentView: View { @State var text = "" var body: some View { List { Color.red.frame(width: 200, height: 500) // When the caret goes to the next line during the text input the scroll doesn't follow it. // So the new text is being overlapped by the keyboard until you scroll manually. TextField( "Run me on iPad and start entering multiline text with keyboard up", text: $text, axis: .vertical ) .lineLimit(1...) Color.red.frame(width: 200, height: 500) } } }
Topic: UI Frameworks SubTopic: SwiftUI
Replies
0
Boosts
0
Views
67
Activity
3w
Avoiding crashes in iOS 27 when selected tab is hidden from TabView
I read through the iOS 27 release notes and the following caught my attention: In apps built with the iOS 27.0 and iPadOS 27.0 SDKs, a TabView enforces that its selection is set to a visible tab. TabView might crash when its selection is set to a hidden or otherwise unavailable tab. (164516837) My app has a partially configurable tab bar. If the user currently has tab X selected (in the TabView) and then chooses to hide tab X (by toggling an option in my app's settings), then I guess this could cause a crash. My app already has logic in place so that if the user hides the tab that is currently the selected tab, then the currently selected tab is changed to another one that is always visible. This is handled by an .onChange view modifier (basically: on change of setting, if selected tab is now hidden, change selected tab to something else). However, I'm concerned about the potential for race conditions with this set up. For example, if the TabView re-renders before the selected tab is changed to an available tab, then this could cause a crash. My questions for Apple: Are programmatically configurable TabViews officially supported, or are you recommending against this practice? If they are, what defensive steps are recommended to avoid crashes (e.g. adding a small delay to make sure that the selected tab is changed first before removing a tab from the TabView).
Topic: UI Frameworks SubTopic: SwiftUI
Replies
2
Boosts
0
Views
140
Activity
3w
Different keyboards show up for KeyboardType .decimalPad
Environment: iOS 26; iPad Mini/Air/Pro Problem: In a TextField, I am using a keyboard with the type .decimalPad. When I initially tap into the TextField, the "popover" keyboard (i.e. the decimalPad) shows up and focusses the TextField. However, when I click outside the TextField (to dismiss the keyboard), the TextField is still focussed (the keyboard was dismissed though). When reentering in the TextField, another keyboard (from the bottom of the screen) appears (most likely .numeric). Does anybody know how to solve this? What I already tried: I tried listening to the dismissal of the keyboard to manually set the FocusState to nil. However, the dismissal of the "popover/decimal" keyboard is not recognized as such a dismissal. I also tried to build a custom component out of that, but then I lose the TextField behavior, conflicting with HIG.
Replies
2
Boosts
0
Views
280
Activity
3w