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

AppKit Documentation

Post

Replies

Boosts

Views

Activity

When to call noteHeightOfRows when cell view changes size?
I have a tableview with a column which has an inner tableview. I want to change height of the outer tableview to match the height of the inner tableview. outerTableView.reloadData() let range = outerTableView.rows(in: summaryTableView.superview!.visibleRect) outerTableView.noteHeightOfRows(withIndexesChanged: IndexSet(integersIn: range.lowerBound..<range.upperBound)) The above code will cause an exception: WARNING: NSTableView detected a rowView was requested from inside of the -heightOfRow delegate method. That is not supported! ( 0 CoreFoundation 0x000000019093eccc __exceptionPreprocess + 176 1 libobjc.A.dylib 0x0000000190426788 objc_exception_throw + 60 2 AppKit 0x000000019420be98 -[NSTableRowData _availableRowViewWhileUpdatingAtRow:] + 0 3 AppKit 0x000000019425a470 -[NSTableView viewAtColumn:row:makeIfNecessary:] + 32
1
0
456
Mar ’24
How let scroll event 'sink' to parent view?
I have an uncommon scenario here. outer tableview +--------------------------+ | column 1| inner tableview| +--------------------------+ Now most often the out tableview has many rows and vertical scrollbar visible. When user try to scroll vertically in the inner tableview but it has no vertical scrollbar (because it has only a few items), I want the scroll event sink into its parent view or better outer tableview, so that user does not have to move cursor to first column in outer tableview and scrolls. Is this possible?
1
0
585
Mar ’24
How to override Document's shouldCloseWindowController method in Swift
To me, the documentation for this method is not at all clear and needs to provide sample code. I tried searching the dev site for sample projects, but they're no longer where they lived for decades before. And where's the TextEdit sample project?! I need to override shouldCloseWindowController so I can make sure some sub-windows can be closed before closing the document's one and only window. I've done that, but then have no idea what I'm supposed to do to all the document to close. I tried this, which is what I think the NSDocument version header says to do: if ((self.windowControllers.first?.shouldCloseDocument) != nil){ self.canClose(withDelegate:delegate as Any, shouldClose:shouldCloseSelector, contextInfo:contextInfo); } But the document never gets the close() method called - only the window goes away.
0
0
405
Mar ’24
Multiple NSMenu issues in Sonoma
Sonoma beta release notes mention that NSMenu was rewritten from scratch using AppKit, however, it seems like a lot of behavior was removed along the way which breaks applications. I've filed several requests using Feedback Assistant, but none of them were fixed in the 3 following betas. FB12867496: NSMenu no longer receives keyboard events from GetEventDispatcherTarget (there is a workaround) FB12867573: NSMenuItem custom view window is nil FB12887219 : NSMenu performSelector highlightItem doesn't highlight menu item FB12938907: NSMenu not properly updated when adding/removing NSMenuItem I wonder if anyone else has experienced similar problems and can share workarounds for them:
6
2
1.3k
Aug ’23
A VZMacGraphicsDisplayConfiguration with a large resolution causes macOS Ventura to incorrectly draw its menu bar items.
Filed as rdar://FB11975037 When macOS Ventura is run as a guest OS within the virtualization framework, the main menu bar items will not be displayed correctly if VZMacGraphicsDisplayConfiguration defines a large resolution. The menu bar titles appear to be using the same color as the menu bar itself. When the Appearance is set to Light, the menu bar items are effectively invisible. When the Appearance is set to Dark, the menu bar items are drawn in what looks like a disabled state. This only affects the menu bar item titles on the left-hand side. The date-time and menu bar icons on the right side are always displayed in the correct color. This appears to be a regression in macOS Ventura as this issue is not present in macOS 12 running as a guest. This bug can be easily reproduced using Apple's own Virtualization sample code titled: "Running macOS in a Virtual Machine on Apple Silicon Macs" Steps to reproduce: Follow the sample code instructions for building and installing a VM.bundle. Before running 'macOSVirtualMachineSampleApp', change the VZMacGraphicsDisplayConfiguration to use: width = 5120, height = 2880, ppi = 144. Run 'macOSVirtualMachineSampleApp' and notice that the menu bar titles on the left side of the screen are not correctly drawn in the guest instance. This has been tested on: Host: macOS 13.1 Guest: macOS 13.x (All versions) Hardware: MBP 14" M1 Pro 32GB/2TB Is there anything that can be done to resolve this issue?
4
2
1.4k
Jan ’23
Any way to keep app running while keep main window hidden?
I tried many ways but it seems I just cannot get it working. // AppDelegate func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true // false does not work either } // MainWC func windowShouldClose(_ sender: NSWindow) -> Bool { print(#function) if sender === NSApp.mainWindow { print("is main window") sender.setIsVisible(false) return false } return true } Once I hide the main window (using setIsVisible or orderOut) the app quits; even if I return false from applicationShouldTerminateAfterLastWindowClosed, NSApp.mainWindow will become nil.
1
0
569
Mar ’24
updating CommandLine.arguments on repeated 'open -a' commands
Wanted to add some basic scripting capabilities for an AppKit Swift application on macOS. I looked at adding AppleScript support (i.e. Cocoa Scripting) and it, frankly, hurts my head. I then discovered that Swift provides for CommandLine.argc and Commandline.arguments. So, from Terminal, I can do open -a myApp --args arg1 arg2 arg3 and sure enough, MyApp starts and CommandLine.arguments contain arg1, arg2, arg3 along w/ the first entry which is the fully resolved path of the executable. Great! However, if myApp is already running when I execute open -a myApp --args arg4 CommandLine.arguments are not updated and I get the same values as when I originally started the program (i.e. arg1, arg2, arg3 and not arg4). So I added func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool { parseCommandLine(); return true} to AppDelegate and while parseCommandLine is called for my second open -a command, it still points to the old CommandLine.arguments. Even tried returning false, but no difference. Is there a way for CommandLine to be refreshed if myApp is already running? Or a different way to get the same effect?
0
0
346
Mar ’24
How change NSTableView's width using code?
I calculate cell view's width in func tableView(_ tableView: NSTableView, sizeToFitWidthOfColumn column: Int). I have a need to resize the tableview's width to just match total width of all cell views' (without scrollbars). But it seems changing tableview's width does not work: tableView.bounds.size = CGSize(width: w, height: tableView.bounds.height) I suspect that I should change its clipping view or enclosing scrollview, but don't have any idea on this. Any help?
0
0
479
Mar ’24
Crash When Clicking on Definition View Created by AppKit's showDefinition(for:at)
I'm encountering a crash issue in my macOS application when clicking on the view generated by AppKit's showDefinition(for:at) function. I'm seeking assistance to resolve this issue. **Problem Description: ** I'm developing a macOS application where I utilize the showDefinition(for:at) function provided by AppKit to display the definition view of words. However, whenever I click on this view, the application crashes abruptly. **Error Message: ** The crash log reveals the following error message: Fault: deferNSXPCInvocationOntoMainThread_block_invoke caught NSInternalInconsistencyException '_CPSSetFrontProcessWithOptions failed due to CGError -606 4294966690 fffffda2 (appIsDaemon)' Attempts Made: Tried wrapping relevant code blocks with DispatchQueue.main.async, suspecting a threading issue. Making the DefinitionWindow variable a global one to manually control its lifecycle Development Environment: macOS Version: 14.3.1 Xcode Version: 15 Below is a complete and reproducible code snippet that can be directly executed within a terminal project template. Please note that it requires Accessibility permissions to be granted in the Privacy settings. import Cocoa import SwiftUI import AppKit class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ notification: Notification) { NSEvent.addGlobalMonitorForEvents(matching: .keyDown) { [weak self] event in guard let self = self else { return } if event.modifierFlags.contains(.command) && event.charactersIgnoringModifiers == "c" { self.ShowWordDefinition() } } NSApp.servicesProvider = self NSApp.registerServicesMenuSendTypes([.string], returnTypes: []) } func ShowWordDefinition(){ DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { let attributedString = NSAttributedString(string:NSPasteboard.general.string(forType: .string)!) let DefinitionWindow = NSWindow(contentRect: NSRect(origin: .zero, size: NSSize(width: 1, height: 1)), styleMask: [.borderless], backing: .buffered, defer: false) // on the top DefinitionWindow.level = .floating let pointInWindow = NSPoint(x:0,y:0); //default value DefinitionWindow.contentView?.showDefinition(for: attributedString, at: pointInWindow) DefinitionWindow.orderFront(nil) } } } let delegate = AppDelegate() let app = NSApplication.shared app.delegate = delegate app.run() full crash log reveals the following error message: FAULT: deferNSXPCInvocationOntoMainThread_block_invoke caught NSInternalInconsistencyException '_CPSSetFrontProcessWithOptions failed due to CGError -606 4294966690 fffffda2 (appIsDaemon)' with backtrace ( "0 CoreFoundation __exceptionPreprocess + 176", "1 libobjc.A.dylib objc_exception_throw + 60", "2 CoreFoundation +[NSException exceptionWithName:reason:userInfo:] + 0", "3 ViewBridge assertCGError + 80", "4 ViewBridge -[NSRemoteView _serviceWindowWouldActivate] + 724", "5 CoreFoundation __invoking___ + 148", "6 CoreFoundation -[NSInvocation invoke] + 428", "7 ViewBridge __deferNSXPCInvocationOntoMainThread_block_invoke + 120", "8 ViewBridge __wrapBlockWithVoucher_block_invoke + 56", "9 ViewBridge deferredBlockOpportunity_block_invoke_2 + 360", "10 CoreFoundation __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 28", "11 CoreFoundation __CFRunLoopDoBlocks + 356", "12 CoreFoundation __CFRunLoopRun + 2440", "13 CoreFoundation CFRunLoopRunSpecific + 608", "14 HIToolbox RunCurrentEventLoopInMode + 292", "15 HIToolbox ReceiveNextEventCommon + 648", "16 HIToolbox _BlockUntilNextEventMatchingListInModeWithFilter + 76", "17 AppKit _DPSNextEvent + 660", "18 AppKit -[NSApplication(NSEventRouting) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 716", "19 AppKit -[NSApplication run] + 476", "20 try main + 160", "21 dyld start + 2360" ) Just a reminder, the application will crash when you click on the displayed definition window. Potential Questions and Concerns: Could there be an issue related to UI transitions or the main thread? How exactly does the showDefinition(for:at) process work internally? Maybe , the view's display level being raised when clicked caused conflict? If anyone could provide any insights or guidance on resolving this issue, it would be greatly appreciated. Thank you!
0
0
341
Mar ’24
What is changing the size of my window on first appearance?
I have some old code that a user has prodded me into trying to resolve. The issue is that the window does not size correctly on its first appearance. Stepping through my code, on initial entry to the windowDidLoad method, the size is (800, 472), which seems to correspond with the size in Interface Builder. I go and calculate the size that I want, and in one case it turns out to be (1235, 435), and I use setContentSize to get the window to the correct size. However, it is not that size when it appears, and when I get a chance to look at it, the size is (816, 435). When it runs through the same code in response to the user setting the scale, the size is correctly (1235, 435). Just to be non-deterministic, sometimes the height is 411. The numbers may change, but the difference in height is always either 0 or 24. Is there something that runs after windowDidLoad that changes the window size? Or any other clues to track down why the size changes?
3
0
493
Feb ’24
Print dialog issues with objective-c projects on Sonoma
Hello, I have some older objective-c projects that are about creating reports of tables and gantt charts and printing those reports. They work fine on Ventura and BigSur, but after upgrading to Sonoma, I encountered some problems with the Print dialog and options. Specifically, the page preview is not working, and the Close button does not close the dialog and is not responsive. I have to force quit the app to exit the Print dialog. This makes it impossible to print my reports properly. I wonder if this is a bug with Sonoma or with objective-c, and if there is any workaround or fix for this issue. I appreciate any help or advice from the community or the Apple support team. Thank you.
0
0
427
Feb ’24
Crash When Clicking on Definition View Created by AppKit's showDefinition(for:at)
I'm encountering a crash issue in my macOS application when clicking on the view generated by AppKit's showDefinition(for:at) function. I'm seeking assistance to resolve this issue. Problem Description: I'm developing a macOS application where I utilize the showDefinition(for:at) function provided by AppKit to display the definition view of words. However, whenever I click on this view, the application crashes abruptly. Error Message: The crash log reveals the following error message: Fault: deferNSXPCInvocationOntoMainThread_block_invoke caught NSInternalInconsistencyException '_CPSSetFrontProcessWithOptions failed due to CGError -606 4294966690 fffffda2 (appIsDaemon)' Attempts Made: Tried wrapping relevant code blocks with DispatchQueue.main.async, suspecting a threading issue. Making the DefinitionWindow variable a global one to manually control its lifecycle Development Environment: macOS Version: 14.3.1 Xcode Version: 15 I've included a snippet of the function where the view is created: func ShowDefinition(selectedText : String) { DispatchQueue.main.async { let DefinitionWindow = NSWindow(contentRect: NSRect(origin: self.mouseLocation, size: NSSize(width: 1, height: 1)), styleMask: [.borderless], backing: .buffered, defer: false) DefinitionWindow.level = .floating guard let mainScreenFrame = NSScreen.main?.frame else { return } DefinitionWindow.contentView?.showDefinition(for: attributedString, at: pointInWindow) DefinitionWindow.orderFront(nil) } } Potential Questions and Concerns: Could there be an issue related to UI transitions or the main thread? How exactly does the showDefinition(for:at) process work internally? Maybe , the view's display level being raised when clicked caused conflict? If anyone could provide any insights or guidance on resolving this issue, it would be greatly appreciated. Thank you!
0
0
241
Feb ’24
Crash When Clicking on Definition View Created by AppKit's showDefinition(for:at)
I'm encountering a crash issue in my macOS application when clicking on the view generated by AppKit's showDefinition(for:at) function. I'm seeking assistance to resolve this issue. Problem Description: I'm developing a macOS application where I utilize the showDefinition(for:at) function provided by AppKit to display the definition view of words. However, whenever I click on this view, the application crashes abruptly. Error Message: The crash log reveals the following error message: Fault: deferNSXPCInvocationOntoMainThread_block_invoke caught NSInternalInconsistencyException '_CPSSetFrontProcessWithOptions failed due to CGError -606 4294966690 fffffda2 (appIsDaemon)' Attempts Made: Tried wrapping relevant code blocks with DispatchQueue.main.async, suspecting a threading issue. Development Environment: macOS Version: 14.3.1 Xcode Version: 15.2 I've included a snippet of the function where the view is created: func showWordDefinition(selectedText: String) { DispatchQueue.main.async { let DefinitionWindow = NSWindow(contentRect: NSRect(origin: self.mouseLocation, size: NSSize(width: 1, height: 1)), styleMask: [.borderless], backing: .buffered, defer: false) DefinitionWindow.level = .floating guard let mainScreenFrame = NSScreen.main?.frame else { return } DefinitionWindow.contentView?.showDefinition(for: attributedString, at: pointInWindow) DefinitionWindow.orderFront(nil) } Potential Questions and Concerns: Could there be an issue related to UI transitions or the main thread? How exactly does the showDefinition(for:) process work internally? Maybe , the view's display level being raised when clicked? If anyone could provide any insights or guidance on resolving this issue, it would be greatly appreciated. Thank you!
0
0
228
Feb ’24
How to detect the location of a mouseDown event using Swift?
How to detect the location of a mouseDown event using Swift? With the following code snippet, I get the error "Cannot find type 'NSEvent' in scope"? import SpriteKit func mouseDown(with event: NSEvent) { if let ourScene = GameScene(fileNamed: "GameScene") { let location = event.location(in: view) let node:SKNode = ourScene.atPoint(location) if (node.name == "creditsInfo") { showCredits() } } // if let ourScene } // mouseDown Anybody have a floodlight to shine on this very basic error?
5
0
935
Feb ’24
NSTextList support in macOS 14
This WWDC video (https://developer.apple.com/videos/play/wwdc2022/10090/) shows using NSTextList in TextKit 2 on both iOS and macOS to create bulleted lists in UITextView and NSTextView, respectively. The sample code still works on iOS, but doesn't work on macOS Here's a screenshot from the wwdc talk: Here's the same sample code running on macOS 14.3: Anyone know how to make NSTextList work on macOS 14? Is this a regression, did something change with the api, or has the functionality been removed?
2
3
672
Feb ’24
Issue setting a folder icon on Synology NAS
I have code which uses NSWorkspace setIcon:forFile:options: to place icons on folders. The code works everywhere except on a Synology NAS. (QNAP works fine). The method returns failed regardless of the NSWorkspaceIconCreationOptions set on the call. I would have chalked this up to a driver issue except that the user can manually set the icons on the Finder's Get Info panel. This implies that there is another method that I'm missing. Any ideas as to what this is?
0
0
335
Feb ’24