Construct and manage a graphical, event-driven user interface for your macOS app using AppKit.

Posts under AppKit tag

188 Posts

Post

Replies

Boosts

Views

Activity

Can SwiftUI TextFields in a List on macOS be marked as always editable?
In SwiftUI's List, on macOS, if I embed a TextField then the text field is presented as non-editable. If the user clicks on the text and waits a short period of time, the text field will become editable. I'm aware this is generally the correct behaviour for macOS. However, is there a way in SwiftUI to supress this behaviour such that the TextField is always presented as being editable? I want a scrollable, List of editable text fields, much like how a Form is presented. The reason I'm not using a Form is because I want List's support for reordering by drag-and-drop (.onMove). Use Case A view that allows a user to compose a questionnaire. They are able to add and remove questions (rows) and each question is editable. They require drag-and-drop support so that they can reorder the questions.
0
0
104
May ’25
How do you restore a Sheet's window frame in SwiftUI for macOS
On macOS, it's not uncommon to present windows as sheets that can be resized. By setting the NSWindow's various frame auto save properties, you can restore the size of the sheet the next time it is presented. When presenting a Sheet from within SwiftUI using the .sheet view modifier, how can I preserve and restore the sheet's frame size? The closest I've been able to come is to put the SwiftUI view into a custom NSHostingController and then into an NSViewControllerRepresentable and then override viewWillAppear and look for self.view.window, which is all little awkward. Is there a more idiomatic way to achieve this in "pure" SwiftUI?
2
0
81
May ’25
-applicationDockMenu: method on NSApplicationDelegate doesn't work when attached to debugger
When I add a simple menu to the dock via the NSApplicationDelegate method -applicationDockMenu: and run the app from Xcode it doesn't work. -(NSMenu*)applicationDockMenu:(NSApplication*)sender { NSMenu *dockMenu = [self buildDockMenu]; if (dockMenu != nil) { NSLog(@"Returning dock menu."); return dockMenu; } else { NSLog(@"Not ready to build dock menu"); return nil; } } When I run the app, my main app window shows up but nothing logs out in -applicationDockMenu: until I click outside my app's window (so if I click the desktop background, or a Finder window, or whatever). Then after I click outside my app's main window this logs out: Returning dock menu. The "Not ready to build dock menu" message does not log out. But...when I right click on the dock icon, the menu doesn't show up. But if I stop the app from Xcode and just run it not attached to the debugger, the dock menu does show up. But this makes the debugging/testing situation not ideal.
3
0
96
May ’25
How to correctly set a Picker's selection and contents in SwiftUI for macOS?
How do you atomically set a Picker's selection and contents on macOS such that you don't end up in a situation where the selection is not present within the Picker's content? I presume Picker on macOS is implemented as an NSPopUpButton and an NSPopUpButton doesn't really like the concept of "no selection". SwiftUI, when presented with that, outputs: Picker: the selection "nil" is invalid and does not have an associated tag, this will give undefined results. Consider the following pseudo code: struct ParentView: View { @State private var items: [Item] var body: some View { ChildView(items: items) } } struct ChildView: View { let items: [Item] @State private var selectedItem: Item? var body: some View { Picker("", selection: $selectedItem) { ForEach(items) { item in Text(item.name).tag(item) } } } } When items gets passed down from ParentView to the ChildView, it's entirely possible that the current value in selectedItem represents an Item that is not longer in the items[] array. You can "catch" that by using .onAppear, .task, .onChange and maybe some other modifiers, but not until after at least one render pass has happened and an error has likely been reported because selectedItem is nil or it's not represented in the items[] array. Because selectedItem is private state, a value can't easily be passed down from the parent view, though even if it could that just kind of moves the problem one level higher up. What is the correct way to handle this type of data flow in SwiftUI for macOS?
1
0
141
May ’25
How to reopen a closed SwiftUI WindowGroup window programmatically without user interaction?
I’m building a macOS app using SwiftUI with a WindowGroup(id: "rootWindow") for the main UI. The app shows a countdown timer, and the timer continues to run even after the user closes the main window (clicks the red "X"). When the timer reaches 0, I want to automatically reopen that window and bring the app to the front. I’m currently using the following code to bring the app to the foreground and show the window when the app is still open (but not focused/resign active state): NSApp.activate(ignoringOtherApps: true) NSApp.windows.forEach { window in if window.identifier?.rawValue.starts(with: "rootWindow") { window.makeKeyAndOrderFront(nil) } } However, this doesn’t work when the window has been closed. At that point, NSApp.windows no longer contains my SwiftUI window, and I have no reference to recreate or reopen it. I also cannot use openWindow environment value as it requires a view. How can I programmatically reopen a SwiftUI WindowGroup window after it’s been closed, without requiring any user interaction (like clicking the Dock icon)?
2
0
94
May ’25
Is it reasonable to vend an NSView from a "ViewModel" when using NSViewRepresentable instead of implementing the Coordinator pattern?
I'm currently integrating SwiftUI into an AppKit based application and was curious if the design pattern below was viable or not. In order to "bridge" between AppKit and SwiftUI, most of my SwiftUI "root" views have aViewModel that is accessible to the SwiftUI view via @ObservedObject. When a SwiftUI views need to use NSViewRepresentable I'm finding the use of a ViewModel and a Coordinator to be an unnecessary layer of indirection. In cases where it makes sense, I've just used the ViewModel as the Coordinator and it all appears to be working ok, but I'm curious if this is reasonable design pattern or if I'm overlooking something. Consider the following pseudo code: // 1. A normal @ObservedObject acting as the ViewModel that also owns and manages an NSTableView. @MainActor final class ViewModel: ObservedObject, NSTableView... { let scrollView: NSScrollView let tableView: NSTableView @Published var selectedTitle: String init() { // ViewModel manages tableView as its dataSource and delegate. tableView.dataSource = self tableView.delegate = self } func reload() { tableView.reloadData() } // Update view model properties. // Simpler than passing back up through a Coordinator. func tableViewSelectionDidChange(_ notification: Notification) { selectedTitle = tableView.selectedItem.title } } // 2. A normal SwiftUI view, mostly driven by the ViewModel. struct ContentView: View { @ObservedObject model: ViewModel var body: some View { Text(model.selectedTitle) // No need to pass anything down other than the view model. MyTableView(model: model) Button("Reload") { model.reload() } Button("Delete") { model.deleteRow(...) } } } // 3. A barebones NSViewRepresentable that just vends the required NSView. No other state is required as the ViewModel handles all interactions with the view. struct MyTableView: NSViewRepresentable { // Can this even be an NSView? let model: ViewModel func makeNSView(context: Context) -> some NSView { return model.scrollView } func updateNSView(_ nsView: NSViewType, context: Context) { // Not needed, all updates are driven through the ViewModel. } } From what I can tell, the above is working as expected, but I'm curious if there are some situations where this could "break", particularly around the lifecycle of NSViewRepresentable Would love to know if overall pattern is "ok" from a SwiftUI perspective.
0
0
49
Apr ’25
The @Environment(\.dismiss) value in SwiftUI for macOS does not dismiss a sheet presented by an NSWindowController.
I'm wondering what the correct, or recommended, way is to dismiss a SwiftUI that is being presented as a sheet hosted by an NSHostingController. The usual technique of invoking @Environment(\.dismiss) does not appear to work. Consider the code below. An NSWindowController is attempting to display a SwiftUI SettingsView as a sheet. The sheet is correctly presented, but the SettingsView is unable to dismiss itself. I am able to make it work by passing a closure into SettingsView that calls back to the NSWindowController but it's rather convoluted because SettingsView doesn't know the view controller that's hosting it until after SettingsView has been created, which means "finding" that view controller in the window controller to dismiss is more involved than it should be. Is there a better strategy to leverage here? final class MyViewController: NSViewController { @IBAction func buttonClicked(_ sender: NSButton) { if let presenter = window?.contentViewController { presenter.presentAsSheet(NSHostingController(rootView: SettingsView())) } } } struct SettingsView: View { @Environment(\.dismiss) private var dismiss var body: some View { VStack { Button("Cancel", role: .cancel) { dismiss() // This call does not dismiss the sheet. } .keyboardShortcut(.cancelAction) } } } Thank you. macOS 15.4.1 (24E263), Xcode 16.3 (16E140)
0
0
64
Apr ’25
Overriding NSDocument.prepareSavePanel(_:) hides file format popup button
I would like to provide a default filename when saving a document depending on the document data. I thought I could do so by overriding NSDocument.prepareSavePanel(_:) and setting NSSavePanel.nameFieldStringValue, but simply implementing that method seems to hide the file format popup button shown by default (see image). Calling super doesn't help. Is it possible to set a default filename and keep the file format popup button? On macOS 15, I can toggle NSSavePanel.showsContentTypes, but how about macOS 14 and older?
Topic: UI Frameworks SubTopic: AppKit Tags:
4
0
79
Apr ’25
NSTableView.clickedRow sometimes is greater than number of rows
Xcode has been downloading many similar crash reports for my app for some time now, related to an index out of range runtime exception when accessing a Swift array. The crashes always happen in methods triggered by user input or during menu item validation when I try to access the data source array by using the following code to determine the indexes of the relevant table rows: let indexes = clickedRow == -1 || selectedRowIndexes.contains(clickedRow) ? selectedRowIndexes : IndexSet(integer: clickedRow) I was never able to reproduce the crash until today. When the app crashed in the Xcode debugger, I examined the variables clickedRow and selectedRowIndexes.first, which were 1 and 0 respectively. What's interesting: the table view only contained one row, so clickedRow was effectively invalid. I tried to reproduce the issue several times afterwards, but it never happened again. What could cause this issue? What are the circumstances where it is invalid? Do I always have to explicitly check if clickedRow is within the data source range?
Topic: UI Frameworks SubTopic: AppKit Tags:
4
0
72
Apr ’25
How to match Status/Menu Bar font (Date and Time)
Hello, I am trying to match the font and the position of the date and time displayed. This is what it looks like: .font: NSFont.systemFont(ofSize: NSFont.systemFontSize, weight: .regular), .foregroundColor: NSColor.labelColor, .baselineOffset: 0.5 It looks great on built-in display, but on external 4K it is incorrect. The baselineOffest is unnecessary, and the font looks skinny in comparison. Can anyone comment on such issue?
5
0
115
Apr ’25
Does MKLookAroundViewController work on macOS?
Trying to incorporate a LookAroundView into my macOS application but unable to make the LookAroundView interactive at all. I can get it to display a static image, but there's no interactivity at all and no controls visible. This is using the SwiftUI LookAroundPreview view as well as trying to wrap MKLookAroundViewController inside an NSViewRepresentable. The navigation properties are set to true but that doesn't seem to make a difference. Would love to incorporate this feature but without interactivity its value is limited. macOS 15.4.1 (24E263), Xcode Version 16.3 (16E140)
1
0
84
Apr ’25
How to create a momentary segmented control in SwiftUI for macOS?
In AppKit, NSSegmentedControl has various styles defined by NSSegmentStyle and various tracking modes defined by NSSegmentSwitchTracking. How can we set these properties in SwiftUI? I'm currently using a Picker with the view modifier .pickerStyle(.segmented) applied but this seems to produce a segmented control with tracking set to "select one". In particular I'm looking for momentary tracking so that I can create navigation-style buttons for backward/forward navigation. Under AppKit, the canonical way to do this is an NSSegmentedControl of style separated and tracking momentary. Is that possible under SwiftUI for macOS? (Using the latest versions of everything.)
1
0
95
Apr ’25
VoiceOver incorrect focus on modal alert
When my macOS Cocoa app displays a modal alert with beginSheetModal(for:completionHandler:), VoiceOver sometimes seems to focus on an "illegal" upper level, where any attempts at navigation will give the unhelpful response "Alert, dialog", until you "drill down" with VO + shift + down or switch apps. After that, things will work as expected. Is this a known bug? Does it happen to anybody else, or am I doing something wrong?
3
1
94
Apr ’25
Should i set window.isReleasedWhenClosed to true or leave it to default?
Hi, In mac os swift ui application when i set window.isReleasedWhenClosed and when i close the window the app is getting crashed with exc_bad_access. but when i leave it to default value the app is not crashing. for some windows setting window.isReleasedWhenClosed to true is woking properly when closing the windows. But for some windows it is crashing. If i dont set it to true the window is not removed from NSApplication.shared.windows sometimes. I am confused about setting isReleasedWhenClosed to true Could someone calrify on this please. thank in advance.
2
0
51
Apr ’25
Can SwiftUI on macOS create an NSComboButton?
Without resorting to NSViewRepresentable, is there a view or view modifier in SwiftUI that can create an NSComboButton on macOS? NSComboButton was introduced in macOS 13 and is (relatively) new to AppKit: Apple Developer - NSComboButton I only require support on macOS for this control. Note that this is not to be confused with NSComboBox, which is a completely different control.
1
0
85
Apr ’25
Should you access @State properties from an NSViewController (AppKit / SwiftUI Integration)?
I'm currently working on a project to integrate some SwiftUI components into an existing AppKit application. The application makes extensive use of NSViewControllers. I can easily bridge between AppKit and SwiftUI using a view model that conforms to ObservableObject and is shared between the NSViewController and the SwiftUI View. But it's kind of tedious creating a view model for every view. Is it "safe" and "acceptable" for the NSViewController to "hold on" to the SwiftUI View that it creates and then access its @State or @StateObject properties? The lifecycle of DetailsView, a SwiftUI View, isn't clear to me when viewed through the lens of an NSViewController. Consider the following: import AppKit import SwiftUI struct DetailsView: View { @State var details: String = "" var body: some View { Text(details) } } final class ViewController: NSViewController { private let detailsView: DetailsView init() { self.detailsView = DetailsView() super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { view.addSubview(NSHostingView(rootView: detailsView)) } func updateDetails(_ details: String) { // Is this 'safe' and 'acceptable'? self.detailsView.details = details } } Is the view controller guaranteed to always be updating the correct @State property or is there a chance that the view controller's reference to it somehow becomes stale because of a SwiftUI update?
2
0
80
Apr ’25
Animated scale effect causes NSCursor to reset in SwiftUI macOS app
For my macOS app, I'm trying to change the mouse cursor to a pointing hand while hovering over a specific view. However, when the view is scaled with an animation triggered by hovering (using .scaleEffect() and .animation()), the cursor doesn't change as expected. Is there any workaround to fix this? This is a sample code: struct ContentView: View { @State private var hovering = false var body: some View { VStack { Text("Hover me") .padding() .background(hovering ? Color.blue : Color.gray) .scaleEffect(hovering ? 1.2 : 1.0) .animation(.linear(duration: 0.2), value: hovering) .onHover { hovering in self.hovering = hovering if hovering { NSCursor.pointingHand.push() } else { NSCursor.pop() } } } .frame(width: 200, height: 200) } } This is how it works: As you can see, when the pointer enters the view, the cursor changes momentarily before reverting back to the arrow icon. I also tried using NSTrackingArea with an NSView placed over the view, but it did not solve the issue. It might be that the combination of .scaleEffect() and .animation() is causing a forced cursor reset (possibly related to the use of NSWindow.disableCursorRects() or something similar). However, I'm not entirely sure. Any insights or suggestions would be greatly appreciated. Thanks!
2
0
90
Apr ’25
Security scoped bookmarks not valid anymore in macOS 14.7.5 / 13.7.5
Security scoped bookmarks that were created before updating to macOS 14.7.5 cannot be resolved anymore after updating to macOS 14.7.5. Reproduction: Sandboxed app on macOS version 14.7.4 Create and store a security scoped bookmark to a user selected folder: let url: URL = <user selected url from NSOpenPanel> let data = try url.bookmarkData(options: [.withSecurityScope], includingResourceValuesForKeys: nil, relativeTo: nil) <persistently store data> Update to macOS 14.7.5 Resolve the previously stored bookmark: let data: Data = <restore data from persistent storage> var stale: Bool = true let url = try URL(resolvingBookmarkData: data, options: [.withSecurityScope], relativeTo: nil, bookmarkDataIsStale: &stale) Expected: The bookmark is resolved correctly and the resulting url can be used to access the folder/file in the sandboxed app after starting access. Observed: URL(resolvingBookmarkData:) throws an error: Error Domain=NSCocoaErrorDomain Code=259 "The file couldn’t be opened because it isn’t in the correct format." New security scoped bookmarks created on macOS 14.5.7 can be resolved without issue. The same appears to happen with macOS 13.7.5. Entitlements: com.apple.security.app-sandbox com.apple.security.files.bookmarks.app-scope com.apple.security.files.user-selected.read-write This is very disruptive, as it appears that Sandboxed apps cannot access any previously stored bookmarks anymore. Particularly after the recent ScopedBookmarkAgent issues in 14.7.1 and 15.0, which were resolved in 14.7.3/15.1 respectively: https://developer.apple.com/forums/thread/764435
12
0
149
Apr ’25