In macOS, I am encountering an issue where the system API fails to grant permission to open a file despite enabling the necessary Read/Write permissions within the SandBox. Could you please elucidate the reasons behind this behavior? Thanks!
func finderOpenFileSystem(at path: String) {
let fileURL = URL(fileURLWithPath: path)
guard FileManager.default.fileExists(atPath: path) else {
print("Error: File does not exist at path: \(path)")
return
}
let success = NSWorkspace.shared.open(fileURL)
if success {
print("File opened successfully: \(fileURL)")
} else {
print("Error: Failed to open file: \(fileURL)")
}
}
AppKit
RSS for tagConstruct and manage a graphical, event-driven user interface for your macOS app using AppKit.
Posts under AppKit tag
184 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
When scrolling a basic NSScrollView there seems to be a sudden jump after each flick. Scrolling does not appear smooth and is disorientating.
A scroll jump seems to happen directly after letting go of a scroll flick using a trackpad/mouse. Right at that moment the scroll turns into a momentum scroll, slowly decreasing the speed. But the first frame after the gesture the content jumps forward, more than what is expected.
Observations:
Counterintuitively, scrolling appears to be smoother when disabling NSScrollView.isCompatibleWithResponsiveScrolling. If disabled using a custom NSScrollView subclass there is no large jump anymore.
Scrolling also appears to be smoother using a SwiftUI ScrollView. I assume that has the same behaviour as a disabled isCompatibleWithResponsiveScrolling
Ironically a WKWebView scrolls much smoother. No sudden jump is observable. It also seems to scroll with faster acceleration, but the individual frames do appear smoother. Why is this better than a native NSScrollView?
Elastic scrolling at the bounds of the scroll view also appears much smoother for WKWebViews. When pulling to refresh there is a jump for NSScrollView/SwiftUI, but not for WKWebView.
When using an NSScrollView with isCompatibleWithResponsiveScrolling disabled, scrolling appears just as smooth as WKWebView on macOS 13 Ventura and below. On macOS 14 Sonoma scrolling behaviour is suddenly different.
Please see a sample project with 4 different scroll views side by side:
https://github.com/floorish/ScrollTest
Screen recordings show the sudden jumps when scrolling and when elastic scrolling.
Tested on Intel & Arm Macs, macOS 11 Big Sur through 15 Sequoia, built with Xcode 16.
Should isCompatibleWithResponsiveScrolling be disabled on Sonoma+? Are there any drawbacks?
There is also no overdraw anymore since Monterey, as described in https://developer.apple.com/library/archive/releasenotes/AppKit/RN-AppKitOlderNotes/#10_9Scrolling
Even with responsive scrolling disabled, why is WKWebView scrolling much smoother than NSScrollView?
I have an application that binds a menu item to trigger on ⌘]. When I set the US input source, I press ⌘] in order to trigger that item. However, when I switch the input source to QWERTZ (German), the trigger changes to ⌘Ä automatically by the OS. It seems to translate keystrokes for different input sources.
The problem is that I also render the keybindings in a window in my application, and my application is not aware of this translation. Furthermore, I have other key shortcuts in my application which are not bound to menu items, and I want to make sure those get translated too.
Does AppKit expose a way to lookup what a keystroke will be when MacOS translates it, i.e. lookup ⌘Ä from ⌘] when the current layout is QWERTZ? I can't find anything in Apple's docs.
I tried converting a character to virtual key code based on the US layout and then mapping it back to a character based on the QWERTZ layout. That doesn't seem to be the same b/c that ends up converting ] to + instead which seems to be based on physical key location, different from how the keybindings are handled.
Update: I notice similar behavior for VS Code's menu bar, e.g. in their "Terminal" menu. Switching to German changes some bindings. This does not occur at all in iTerm's menu bar, I suspect b/c their menu items are specified in a different way, xib files with hard-coded key equivalents
Let's say I want to build a simple photo management app on Mac or iPad with Swift UI. This app has multi-window support. My photos are organized inside albums. I should be able to drag photos between windows from one album to another.
I struggle to get this working properly with Swift UI. Writing modern code I would like to use Transferable. Let's say my photos are not real files. So I can't use a FileRepresentation. Instead I use CodableRepresentation and encode an identifier. This identifier is later used to drive the move operation between folders.
I ran into some limitations here
Transferable seems to be meant for copy-like Drag & Drop operations. I have no possible to get a "move" cursor on macOS (it's always the copy cursor with the green + sign). Also the API reads like it is about importing/exporting – not moving.
When using dropDestination on ForEach, I completely lack the possibility to deny a drop (e.g. when a photo is already part of the album).
I'd like to have modifier key to switch between copying and moving.
Sometimes a drop should be redirected to a different index. How to do that?
Is there any chance to do this with Transferable? It even doesn't seem to be easy with NSItemProvider and onDrop/onDrag? Or should we still use a plain old UICollectionView/NSCollectionView, if we want to have more sophisticated control over drag/drop validation?
Hi, we are developing a cross-platform library for creating desktop applications in C++: https://github.com/aseprite/laf
For this reason, in macOS, we cannot rely on the default NSApplication.run() event loop, so we decided to implement our custom event loop using the nextEventMatchingMask method.
Then, when a window is in fullscreen mode, for some reason the window stops receiving mouseMove events when the mouse pointer enters an area at the top of the window.
You can see this issue in action by trying the following example project:
https://github.com/martincapello/custom-event-loop-issue
This project just opens one window and uses a custom event loop, it displays the current mouse position at every mouseMove event received, and when the aforementioned area is entered it suddenly stops updating.
There is also a video showing how to reproduce it.
I was able to see that when the position stops updating, we still receive mouseMove events, but for a different window, a borderless window that is added to the NSApplication.windows collection when switching to fullscreen, and which seems to be taken the mouseMove events before reaching the main window.
Also, this issue doesn't happen when using the default NSApplication.run method, despite the borderless windows being added as well.
macOS 15 includes a neat section in System Preferences Settings to change the dynamic text size, as outlined see: https://support.apple.com/guide/mac-help/make-text-and-icons-bigger-mchld786f2cd/mac
However, it's not immediately clear a) how to get one's app in this list, and b) if the usual methods from iOS to react to text size even work on macOS. Does anyone have any experience here? Or should I implement my own controls in my app's settings and call it a day?
For context, my app is a macOS-native SwiftUI app.
How do I implement the same Navigation split view with a side bar in Appkit?
Basically I have this code:
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationSplitView {
// Sidebar
List {
NavigationLink("Item 1", value: "Item 1 Details")
NavigationLink("Item 2", value: "Item 2 Details")
NavigationLink("Item 3", value: "Item 3 Details")
}
.navigationTitle("Items")
} content: {
// Main content (detail view for selected item)
Text("Select an item to see details.")
.padding()
} detail: {
// Detail view (for the selected item)
Text("Select an item from the sidebar to view details.")
.padding()
}
}
}
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
and wanted to somehow convert it to Appkit. I tried to use an NSSplitViewController but I still don't have that side bar and that button to collapse it, how do I go about this?
I'm developing a macOS application and facing an issue with NSTextField delegates after refactoring my code. Here's the situation:
I have an NSWindowController.
Inside the NSWindowController, there's a container NSView named containerView.
On top of containerView, I added a custom NSView subclass named MyDetailsView.
MyDetailsView has two NSTextField instances, and their delegates are properly set. The delegate methods like controlTextDidChange(_:) were getting called as expected.
Due to some additional requirements, I refactored MyDetailsView into MyDetailsViewController, a subclass of NSViewController.
I created a corresponding .xib file for MyDetailsViewController.
Updated the code to load and add MyDetailsViewController's view (view property) to containerView.
Verified that the NSTextField delegates are still being set, and the fields are displayed correctly in the UI.
However, after this refactor, the NSTextField delegate methods (e.g., controlTextDidChange(_:)) are no longer being triggered.
**What I've Tried: **
Verified that the delegates for the NSTextField instances are correctly set after the refactor. Ensured that the MyDetailsViewController's view is added to containerView.
Question: What
could be causing the NSTextField delegate methods to stop working after refactoring from NSView to NSViewController?
@IBOutlet weak var customeView: NSView!
var myDetailsViewController: MyDetailsViewController!
var myDetailsView: MyDetailsView!
var isViewController: Bool = true
override func windowDidLoad() {
super.windowDidLoad()
if isViewController {
myDetailsViewController = MyDetailsViewController(nibName: "MyDetailsViewController", bundle: nil)
self.customeView.addSubview(myDetailsViewController.view)
} else {
myDetailsView = MyDetailsView.createFromNib()
self.customeView.addSubview(myDetailsView!)
}
}
override func showWindow(_ sender: Any?) {
super.showWindow(nil)
window?.makeKeyAndOrderFront(nil)
}
override var windowNibName: NSNib.Name? {
return NSNib.Name("MyWindowController")
}}
class MyDetailsViewController: NSViewController {
@IBOutlet weak var textField: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
}
extension MyDetailsViewController: NSTextDelegate {
func controlTextDidChange(_ obj: Notification) {
guard let textField = obj.object as? NSTextField else { return }
print("The value is ----> (MyDetailsViewController) \(textField.stringValue)")
}
}
TextField delegate is set in XIB.
I am making a framework in C++ using metal-cpp, basically a small game engine. I am also consequently using metal-cpp-extensions provided in LearnMetalCPP to make applications work.
For one of my classes, I needed to add AppKit.hpp inside a public header file, so I moved it and its associate headers(NSApplication.hpp, NSMenu.hpp, etc.) from Project headers to Public in Build Phases' Headers, however, it started giving me the error "cast of C pointer type 'void *' to Objective-C pointer type 'Class' requires a bridged cast" at several points in the AppKit headers. They don't appear when AppKit and its associates are in the Project headers, or when they are in the Private headers and no headers import it.
I imagined that disabling Objective-C ARC and Using __bridge casts outside of ARC in Build Settings would solve it, but it didn't budge.
I imagined it wouldn't involve actively changing the headers would be the answer, but even if I try to put __bridge before the problematic casts, it didn't recognize __bridge.
How do I solve this? And why is it only happening in Public and not Project headers?
I recieve the error message "XOJITError: Could not create code file directory for session: Permission denied". I'm Using Xcode 16.2.
It is an AppKit project using SwiftUI and it also happens if I create a clean project.
Error log is attached.
previews_diagnostics_summary.txt
I've been experiencing a bug when trying to open a file on a remote machine through File -> Open... -> Network -> Connect As... where the Name/Password dialog won't let me enter more than one character into its text fields.
I'm able to get one more character in by toggling between the "Registered User" and "Guest" radio buttons, and it seems to fix itself entirely when I focus on another window before entering my credentials. Once it is "fixed", it doesn't happen again until the machine's restarted.
I was able to reproduce this on 15.1 and 15.1.1, but not on 15.0.1 (I do not currently have access to a machine running 15.2).
Here are some reproduction steps: (You will need a shared computer on LAN)
Restart your machine (un-check reopen windows when logging back in)
Open TextEdit
From the Menu Bar, click “File > Open...”
Select “Network” from the Open Dialog’s sidebar
Select your shared computer on LAN and click “Connect As…”
Try typing in the password field. This will only allow the first key press to produce a character in the text field. (In my case, the Name field was already populated, so the password field was automatically selected)
(Filed as FB16039397)
I have a MacOs AppKit app. This app we are developing for examination purposes. We dont want the user to screen record and also to take screen shot.
We created a window and set the sharingType to none. also we have set window.level to CGShieldingWindowLevel()
Below is the code
if let window = NSApp.windows.first {
window.title = "Test"
window.sharingType = .none // Disable screen capture and recording
window.level = NSWindow.Level(rawValue: Int(CGShieldingWindowLevel())) //
}
As per documentation the windows should be excluded from screen capture and also recording
But the window is excluded only from screen capture and not from screen recording. Please give us a solution to prevent screen recording in MacOs native app.
When putting a TextField into a TableColumn, and while editing, the text exceeds the column width - any way to automatically resize the width to match the entered text ?
Hi,
On macOS, there seems to be a NSTableViewDiffableDataSource and an NSCollectionViewDiffableDataSource, but there seems to be nothing for NSOutlineView. Is it possible to somehow use NSTableViewDiffableDataSource with NSOutlineView that I'm missing?
If not, is it possible to use NSTableView with NSTableViewDiffableDataSource to show a 'table' with section headers?
In one of my apps I use an app group to share data between the app and a command line tool. This works as expected. The app also contains a Dock Tile plugin and I wonder if there's a way to access the group container from this plugin? Thanks in advance for your help.
Best regards,
Marc
So I'm following this code here where I'm using a tableview to display the files contained in a folder along with a group cell to display the name of the current folder:
Here's my tableView:isGroupRow method: method which basically turns every row with the folder name into a group row (which is displayed in red in the previous image ).
-(BOOL)tableView:(NSTableView *)tableView isGroupRow:(NSInteger)row
{
DesktopEntity *entity = _tableContents[row];
if ([entity isKindOfClass:[DesktopFolderEntity class]])
{
return YES;
}
return NO;
}
and here's my tableView:viewForTableColumn:row: method where I have two if statements to decide whether the current row is a group row (meaning it's a folder) or an image:
-(NSView*)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row;
{
DesktopEntity *entity = _tableContents[row];
if ([entity isKindOfClass:[DesktopFolderEntity class]])
{
NSTextField *groupCell = [tableView makeViewWithIdentifier:@"GroupCell" owner:self];
[groupCell setStringValue: entity.name];
[groupCell setFont:[NSFont fontWithName:@"Arial" size:40]];
[groupCell setTextColor:[NSColor magentaColor]];
return groupCell;
}
else if ([entity isKindOfClass:[DesktopImageEntity class]])
{
NSTableCellView *cellView = [tableView makeViewWithIdentifier:@"ImageCell" owner:self];
[cellView.textField setStringValue: entity.name];
[cellView.textField setFont:[NSFont fontWithName:@"Impact" size:20]];
[cellView.imageView setImage: [(DesktopImageEntity *)entity image]];
return cellView;
}
return nil;
}
Now, if the current row is an image, I change its font to Impact with a size of 40 and that works perfectly, the problem here is with the first IF statement, for a group row I wanted to change the font size to arial with a size of 40 with a magenta color but for some reason I can only get the color to work:
You can see that my changes to the font size didn't work here, what gives?
How can I change the font size for the group row ?
Developing on Monterey 12.7.5
I'm having trouble with updating subitems on NSToolbarItemGroup when selecting the item directly from the NSToolbar items array.
I select the group item off the items array on the toolbar, and then call setSubitems: on the item, with a new array of NSToolbarItems. The group item disappears from the toolbar. It seems to leave a blank invisible item in the toolbar taking up space. I can't manually reinsert the item into the toolbar until I drag out the blank item, then drag back in the real item. Once dragged back in from the palette it displays correctly.
The workaround I've come up with is to remove the item with NSToolbar removeItemAtIndex: and reinsert it with NSToollbar insertItemWithItemIdentifier:atIndex:. This works to update the subitems.
Every other toolbar item property that I've tried has been able to update the item directly in the toolbar. It's only the group item's subitems that don't want to update correctly.
Is there a correct way to do this that I'm missing? Calling [toolbar validateVisibleItems] didn't seem to help.
I am using the window.level set to .floating as described here:
https://developer.apple.com/documentation/appkit/nswindow/level
The setting itself works okay. However, in a multi monitor setup, the floating window is appearing on both the screens.
How can I prevent this? My users report that before macOS Sonoma, this used to not happen. Has this behaviour changed? How can I revert back to the old behaviour?
I am trying to understand why I am seeing crash reports for my code that creates a view from a NIB like the code below. The crash occurs when referencing contentView which should have been bound when the NIB was loaded.
Am I missing something here other than checking the result of the loadNibNamed function call?
class MyView: NSView {
@IBOutlet var contentView: NSView!
init() {
super.init(frame: NSRect(x: 0, y: 0, width: 84.0, height: 49.0))
commonInit()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func commonInit() {
Bundle.main.loadNibNamed("MyView", owner: self, topLevelObjects: nil)
translatesAutoresizingMaskIntoConstraints = false
contentView.translatesAutoresizingMaskIntoConstraints = false
addSubview(contentView)
contentView.frame = self.bounds
}
When I upgraded to Sequoia 15.1, an app that worked fine under OS 14 stopped working. Out of 4 views on the main screen, only 1 is visible. Yet, if I click where another view should be, I get the expected action so the views are there, just not visible. Only I can't see where I am clicking!
I had to upgrade to Xcode 16 to recompile the app and run it in Debug mode. When I do, I get the following:
NSBundle file:///System/Library/PrivateFrameworks/MetalTools.framework/ principal class is nil because all fallbacks have failed.
Can't find or decode disabled use cases.
applicationSupportsSecureRestorableState
FWIW - the only view that actually shows up is the last subview added to the main view.