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

Posts under AppKit tag

170 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Icon for some menu items cannot be removed on macOS 26
create a sample XCode project using Objective-C and stroybook (xib) using latest XCode beta open MainMenu.xib, and select Main Menu → File → Print... remove the image like below 4. build it 5. run it on macOS 26 beta 7 6. The menu item "print.." still have "Image" Is there any way to remove image for one menu item. I have also tried NSMenuItem.image = nil, but still not work. The issue I met on my own app is that I cannot remove icons for "Zoom In", "Zoom Out" and many other menu items, which makes the menu items not aligned properly.
0
0
76
11h
How to differentiate between user-generated NSEvents and programmatically posted events in AppKit?
Hi all, In my AppKit app, I sometimes simulate events programmatically, for example: func simulateKeyPress(characters: String, keyCode: UInt16) { guard let keyDown = NSEvent.keyEvent( with: .keyDown, location: .zero, modifierFlags: [], timestamp: 0, windowNumber: NSApp.mainWindow?.windowNumber ?? 0, context: nil, characters: characters, charactersIgnoringModifiers: characters, isARepeat: false, keyCode: keyCode ) else { return } NSApp.postEvent(keyDown, atStart: false) } At the same time, I install a local event monitor: NSEvent.addLocalMonitorForEvents(matching: .any) { event in // Ideally, detect whether this event came from a real user // (mouse, keyboard, trackpad, etc.) // or was programmatically generated via NSEvent + postEvent. return event } The problem: Events I generate with NSEvent.* factory methods and post using NSApp.postEvent look the same as real system events when received in the monitor. My question: Is there a supported way to tell whether an incoming NSEvent is system/user-generated vs programmatically posted?
Topic: UI Frameworks SubTopic: AppKit Tags:
1
0
39
5h
macOS Document-Based SwiftUI App: “Save” menu item not localized in French
Hi everyone, I’ve run into a strange localization issue with macOS document-based apps in SwiftUI/AppKit. I created a standard document-based macOS app in Xcode (SwiftUI template) and added a French localization to the project. All system-generated menu bar commands (File → New, Close, Print, etc.) are correctly translated into French… except for “Save”, which remains in English. To rule out problems in my own code, I created a fresh, unmodified document-based app project in Xcode, and immediately added French localization without touching any code. Same result: all commands are translated except “Save”. This suggests the issue isn’t specific to my app code, but either the project template, or possibly macOS itself. My environment • Xcode version: 16.4 • macOS version: 15.6.1 Sequoia] • Swift: Swift 6 Questions 1. Has anyone else seen this issue with the “Save” command not being localized? 2. Is this expected behavior (maybe “Save” is handled differently from other menu items)? 3. If it’s a bug in the template or OS, is there a known workaround? Thanks for any insights P.S. Please note that I'm a total beginner
3
0
70
9h
Inset or disable NSSheetEffectDimmingView when presenting a sheet?
I have an NSWindow that isn't entirely opaque. When presenting a sheet AppKit overlays the window with NSSheetEffectDimmingView. The problem is the entire window frame is used so NSSheetEffectDimmingView overlays the transparent areas of the window and it looks bad. Is there a clean way to inset NSSheetEffectDimmingView or even perhaps disable this behavior completely so I can draw my own? I'm looking for a clean solution (other than modifying the view hierarchy of NSNextStepFrame) or swizzles which I might have to resort to if there is no other way.
Topic: UI Frameworks SubTopic: AppKit Tags:
0
0
63
3d
NSWindowCollectionBehavior in Full Screen Spaces
The NSWindow collection behavior is supposed to allow for a window to appear in all spaces, even when another window is full screen in that space. However, I cannot get this to work as expected with any combination. This should be as simple as: window.level = .screenSaver window.collectionBehavior = [ .canJoinAllSpaces, .fullScreenAuxiliary, .canJoinAllApplications, .stationary, .ignoresCycle ] If I have a window (Safari for example) which is full screen in its own space, run my app and change to the Safari window's space, my app's window is not visible at all; it will only float on top of windows in non-fullscreen spaces. What am I misunderstanding?
Topic: UI Frameworks SubTopic: AppKit Tags:
0
0
74
4d
NSToolbar Space item rendered with Liquid Glass Background
Hi, I have a NSToolbar in my Mac Catalyst app with a space and flexible space item in it (https://developer.apple.com/documentation/appkit/nstoolbaritem/identifier/space). On macOS Tahoe the space item is being rendered with a Liquid Glass effect and seems to be automatically grouped with the previous item. Is there a way to prevent this? It basically adds some undesired padding next to the previous item and looks add. The flexible space is rendered normally and as before. I am talking about the space right next to the back chevron item. Thanks for any hints!
1
0
84
4d
Resizing text to fit available space
My app displays some text that should appear the same regardless of the container view or window size, i.e. it should grow and shrink with the container view or window. On iOS there is UILabel.adjustsFontSizeToFitWidth but I couldn't find any equivalent API on macOS. On the internet some people suggest to iteratively set a smaller font size until the text fits the available space, but I thought there must be a more efficient solution. How does UILabel.adjustsFontSizeToFitWidth do it? My expectation was that setting a font's size to a fraction of the window width or height would do the trick, but when resizing the window I can see a slightly different portion of it. class ViewController: NSViewController { override func loadView() { view = MyView(frame: CGRect(x: 0, y: 0, width: 400, height: 400)) NSLayoutConstraint.activate([view.widthAnchor.constraint(equalTo: view.heightAnchor, multiplier: 3), view.heightAnchor.constraint(greaterThanOrEqualToConstant: 100)]) } } class MyView: NSView { let textField = NSTextField(labelWithString: String(repeating: "a b c d e f g h i j k l m n o p q r s t u v w x y z ", count: 2)) override init(frame frameRect: NSRect) { super.init(frame: frameRect) textField.translatesAutoresizingMaskIntoConstraints = false textField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) addSubview(textField) NSLayoutConstraint.activate([textField.topAnchor.constraint(equalTo: topAnchor), textField.leadingAnchor.constraint(equalTo: leadingAnchor), textField.trailingAnchor.constraint(equalTo: trailingAnchor)]) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func resize(withOldSuperviewSize oldSize: NSSize) { // textField.font = .systemFont(ofSize: frame.width * 0.05) textField.font = .systemFont(ofSize: frame.height * 0.1) } }
Topic: UI Frameworks SubTopic: AppKit Tags:
7
0
118
1w
Printing of NSTextView
I have a document-based macOS app written in Objective-C, and each document window contains a scrollable NSTextView. I know that printing can get complicated if you want to do nice pagination, but is there a quick and dirty way to get basic printing working? As it is, the print panel shows up, but its preview area is totally blank. Here's the current printing part of my NSDocument subclass. - (NSPrintInfo *)printInfo { NSPrintInfo *printInfo = [super printInfo]; [printInfo setHorizontalPagination: NSPrintingPaginationModeFit]; [printInfo setHorizontallyCentered: NO]; [printInfo setVerticallyCentered: NO]; [printInfo setLeftMargin: 72.0]; [printInfo setRightMargin: 72.0]; [printInfo setTopMargin: 72.0]; [printInfo setBottomMargin: 72.0]; return printInfo; } - (void)printDocumentWithSettings:(NSDictionary<NSPrintInfoAttributeKey, id> *)printSettings showPrintPanel:(BOOL)showPrintPanel delegate:(id)delegate didPrintSelector:(SEL)didPrintSelector contextInfo:(void *)contextInfo { NSPrintInfo* thePrintInfo = [self printInfo]; [thePrintInfo setVerticallyCentered: NO ]; NSPrintOperation *op = [NSPrintOperation printOperationWithView: _textView printInfo: thePrintInfo ]; [op runOperationModalForWindow: _docWindow delegate: delegate didRunSelector: didPrintSelector contextInfo: contextInfo]; }
Topic: UI Frameworks SubTopic: AppKit Tags:
2
0
127
2w
Equivalent of coalescedTouchesForTouch in AppKit?
This method on UIEvent gets you more touch positions, and I think it's useful for a drawing app, to respond with greater precision to the position of the Pencil stylus. Is there a similar thing in macOS, for mouse or tablet events? I found this property mouseCoalescingEnabled, but the docs there don't describe how to get the extra events.
Topic: UI Frameworks SubTopic: AppKit Tags:
1
0
150
2w
Bug or Feature: Changes to Window Reopen Behavior in macOS 26
Since macOS 26 Beta 1, I notice that the window reopening behavior had changed. Say there are two desktops (spaces), one might: open an app window in desktop 1 close that window switch to desktop 2 reopen the app window (by click on dock tile, spotlight search...) Prior to macOS 26, that window will always reopen in current desktop. This is IMO the right behavior because these windows are most likely transient (message app, chat app, utilities app or note app). In macOS 26, however, will switch to desktop 1 (where the window is closed) and reopen the window in desktop 1. This is weird to me because: Window is "closed", hence it should not be attached to desktop 1 anymore, unlike minimize. Switching desktop interrupts user's current workflow. It's annoying to switch back specially when there're many desktops. This behavior is inconsistent. Some reopen in current desktop, some reopen in previous desktop. Apps like Music, Notes and Calendar reopened in previous desktop, while Mail, Messages, and Freeform reopened in current desktop. I did a little bit of experiment, and find out that apps that reopened in current desktop are most likely because they take an extra step to release the window when it's closed. I believe this is a bug, so I fire a feedback (FB18016497) back in beta 1. But I did not get any response or similar report from others, to a point that I kinda wonder if this is intended. I can easily force my app to reopen in current desktop by nullifying my window controller in windowWillClose, but this behavior essentially change how one can use the Spaces feature that I think I should bring this up to the community and see what other developers or engineers thinks about it.
Topic: UI Frameworks SubTopic: AppKit Tags:
2
0
130
2w
Why is the nib still loaded even though the class has been registered with NSCollectionView?
I implemented a subclass of NSCollectionViewItem: class ViewItem: NSCollectionViewItem { override func loadView() { self.view = NSView() } } and registed to NSCollectionView: class PictureFrameThemeListView: NSCollectionView { init(viewModel: PictureFrameViewModel) { super.init(frame: .zero) self.register(ViewItem.self, forItemWithIdentifier: .item) } However, when calling makeItem(withIdentifier:for:), the following error is prompted: FAULT: NSInternalInconsistencyException: -[NSNib _initWithNibNamed:bundle:options:] could not load the nib 'Item' in bundle NSBundle What confuses me is that I registered the subclass of NSCollectionViewItem, why do NSCollectionView to init the NSNib?
Topic: UI Frameworks SubTopic: AppKit Tags:
2
0
33
2w
Xcode unit test "Creating more than one Application"
When I try to make a unit test target for my macOS app that uses Objective-C, running tests fails, and the debugging log shows a message "Creating more than one Application". If, on the other hand, when I create the unit test target, I select "None" as the target to be tested, and then add all my sources to that target, my tests work. So, I can get my testing done, but I think I must be doing something wrong. By the way, along with the error message, there is a stack crawl: 0 CoreFoundation 0x00007ff8140410aa __exceptionPreprocess + 242 1 libobjc.A.dylib 0x00007ff813b660b7 objc_exception_throw + 48 2 Foundation 0x00007ff814f19bd8 -[NSCalendarDate initWithCoder:] + 0 3 AppKit 0x00007ff817030062 -[NSApplication init] + 1718 4 XCTestCore 0x000000010774b0df -[XCTestDriver _createTestBundlePrincipalClassInstance] + 82 5 XCTestCore 0x0000000107749338 -[XCTestDriver _runTests] + 111 6 XCTestCore 0x000000010770f194 _XCTestMain + 126 7 libXCTestBundleInject.dylib 0x0000000106e8982d __copy_helper_block_e8_32s + 0 8 CoreFoundation 0x00007ff813fc9a91 __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 12 9 CoreFoundation 0x00007ff813fc99ca __CFRunLoopDoBlocks + 398 10 CoreFoundation 0x00007ff813fc883d __CFRunLoopRun + 898 11 CoreFoundation 0x00007ff813fc7e51 CFRunLoopRunSpecific + 560 12 HIToolbox 0x00007ff81da52f3d RunCurrentEventLoopInMode + 292 13 HIToolbox 0x00007ff81da52b84 ReceiveNextEventCommon + 199 14 HIToolbox 0x00007ff81da52aa8 _BlockUntilNextEventMatchingListInModeWithFilter + 64 15 AppKit 0x00007ff8170689d8 _DPSNextEvent + 858 16 AppKit 0x00007ff817067882 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 1214 17 AppKit 0x00007ff817059ef7 -[NSApplication run] + 586 18 AppKit 0x00007ff81702e111 NSApplicationMain + 817 19 PlainCalc 0x00000001057d0a91 main + 65 20 dyld 0x00007ff813b93418 start + 1896
3
0
118
2w
How can I connect NSTableCellView.textField to a SwiftUI view?
When using NSTableView or NSOutlineView, if you use an NSTableCellView and wire up the .imageView and .textField properties then you get some "free" behaviour with respect to styling and sizing of those fields. (ex: They reflect the user's preferred "Sidebar Icon Size" as selected in Settings. ) If I'm using a SwiftUI View inside an NSTableCellView, is there any way to connect a Text or Image to those properties? Consider the following pseudo code: struct MyCellView: View { let text: String let url: URL? var body: some View { HStack { Image(...) // How to indicate this is .imageView? Text(...) // How to indicate this is .textField? } } } final class MyTableCellView: NSTableCellView { private var hostingView: NSHostingView<MyCellView>! init() { self.hostingView = NSHostingView(rootView: MyCellView(text: "", url: nil)) self.addSubview(self.hostingView) } func configureWith(text: String, url: URL) { let rootView = MyCellView(text: text, url: url) hostingView.rootView = rootView // How can I make this connection? self.textField = rootView.??? self.imageView = rootView.??? } } I'm ideally looking for a solution that works on macOS 15+.
2
0
85
4w
NSTableView.reloadData(forRowIndexes:columnIndexes:) causes wrong subview layout when usesAutomaticRowHeights = true
I have a table view where each row has two labels, one left-aligned and one right-aligned. I would like to reload a single row, but doing so causes the right-aligned label to hug the left-aligned label. Before the reload: After the reload: Reloading the whole table view instead, or disabling automatic row height, solves the issue. Can a single row be reloaded without resorting to these two workarounds? I created FB13534100 1.5 years ago but got no response. class ViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate { override func loadView() { let tableView = NSTableView() tableView.translatesAutoresizingMaskIntoConstraints = false tableView.dataSource = self tableView.delegate = self tableView.usesAutomaticRowHeights = true let column = NSTableColumn() column.width = 400 tableView.addTableColumn(column) let scrollView = NSScrollView(frame: CGRect(x: 0, y: 0, width: 500, height: 500)) scrollView.translatesAutoresizingMaskIntoConstraints = false scrollView.documentView = tableView view = scrollView Timer.scheduledTimer(withTimeInterval: 2, repeats: false) { _ in print("reload") tableView.reloadData(forRowIndexes: IndexSet(integer: 2), columnIndexes: IndexSet(integer: 0)) // tableView.reloadData() } } func numberOfRows(in tableView: NSTableView) -> Int { return 5 } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { let cell = NSTableCellView() let textField1 = NSTextField(labelWithString: "hello") textField1.translatesAutoresizingMaskIntoConstraints = false let textField2 = NSTextField(wrappingLabelWithString: "world") textField2.translatesAutoresizingMaskIntoConstraints = false textField2.alignment = .right let stack = NSStackView(views: [ textField1, textField2 ]) stack.translatesAutoresizingMaskIntoConstraints = false stack.distribution = .fill cell.addSubview(stack) NSLayoutConstraint.activate([stack.topAnchor.constraint(equalTo: cell.topAnchor, constant: 0), stack.leadingAnchor.constraint(equalTo: cell.leadingAnchor, constant: 0), stack.bottomAnchor.constraint(equalTo: cell.bottomAnchor, constant: 0), stack.trailingAnchor.constraint(equalTo: cell.trailingAnchor, constant: 0)]) return cell } }
Topic: UI Frameworks SubTopic: AppKit Tags:
2
0
96
3w
macOS 26: NSTokenField crashes due to NSGenericException caused by too many Update Constraints
This example application crashes when entering any text to the token field with FAULT: NSGenericException: The window has been marked as needing another Update Constraints in Window pass, but it has already had more Update Constraints in Window passes than there are views in the window. The app uses controlTextDidChange to update a live preview where it accesses the objectValue of the token field. If one character is entered, it also looks like the NSTokenFieldDelegate methods tokenField(_:styleForRepresentedObject:) tokenField(_:editingStringForRepresentedObject:) tokenField(_:representedObjectForEditing:) are called more than 10000 times until the example app crashes on macOS Tahoe 26 beta 6. I've reported this issue with beta 1 as FB18088608, but haven't heard back so far. I have multiple occurrences of this issue in my app, which is working fine on previous versions of macOS. I haven't found a workaround yet, and I’m getting anxious of this issue persisting into the official release.
0
0
56
Aug ’25
Sleep State Notification Inconsistencies on MacBook Devices When Unplugged
There are inconsistent behaviors in sleep/wake notification callbacks across different MacBook devices and macOS versions when the device is not connected to power, with or without external displays, entering sleep mode by closing the lid, and waking up from sleep by opening the lid. When monitoring the following Objective-C notifications: NSWorkspaceScreensDidSleepNotification NSWorkspaceScreensDidWakeNotification NSWorkspaceWillSleepNotification NSWorkspaceDidWakeNotification Different devices exhibit varying notification trigger patterns: Some devices trigger all four notifications properly Some devices fail to trigger NSWorkspaceScreensDidWakeNotification Some devices fail to trigger NSWorkspaceDidWakeNotification Some devices fail to trigger NSWorkspaceWillSleepNotification These inconsistencies make it challenging to implement reliable sleep/wake detection logic across different MacBook models and macOS versions.
1
0
65
Aug ’25
[TextKit2] - Wrong document height sometimes ?
Hello 👋 I'm playing with the Apple TextKit2 sample app (particularly on macOS). I found that on some long document the evaluated height given by enumerateTextLayoutFragments API is wrong (or at least not I expect) which imply I can no longer scroll in my document even if I have not reached the end of it (which is not what I expect as you can guess). I'm clearly missing a point here. I can reproduce it on the Apple sample app by only changing the text content: https://developer.apple.com/documentation/UIKit/using-textkit-2-to-interact-with-text Using TextKit2, is it my responsability as developer to check that I've reached end of the scrollview whether not being at the end location of the document and call some specific TextKit2 API to invalidate estimation or something ? Here is an updated version of the Apple sample app with another text content that show the issue. https://drive.google.com/file/d/1jtTD84oqGAG4_A9DfqFl_yHmbLKhF1e8/view?usp=sharing Environment: Xcode 16.4 - macOS 15.6 If someone could help me with this, I would be extremely grateful. It puzzles me. NB: I've observed that resizing the window a bit seems to force a new layout and make TextKit2 returns a more accurate height, ... until you reach the end of the document.
3
0
77
Aug ’25
How to speed-up initial UI rendering faster in AppKit?
I am developing an AppKit application in MacOS with Swift. Our application requires a complex, multi-windowed interface and must deliver a very fast, responsive experience. As a performance test, I built a sample app that creates 3 windows programmatically, each containing 500 NSTextFields (with each text-field assigned 35 different properties). Code flow: https://gist.github.com/Raunit-TW/5ac58ac9c6584f93e2ee201aa8118139 This takes around 77 milliseconds to render the windows - I need to find a way to reduce this time, as low as possible. Thanks.
3
0
121
Aug ’25