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

AppKit Documentation

Posts under AppKit subtopic

Post

Replies

Boosts

Views

Activity

NSTextView.shouldDrawInsertionPoint doesn't work with TextKit 2
The following code only ever causes shouldDrawInsertionPoint to be printed (no drawInsertionPoint), but even if that method returns false, the blinking insertion point is still drawn. On the other hand, with TextKit 1 it works as expected. Is there a way to hide the default insertion point in TextKit 2? My app draws its own. I've filed FB13684251. class TextView: NSTextView { override var shouldDrawInsertionPoint: Bool { print("shouldDrawInsertionPoint") return false } override func drawInsertionPoint(in rect: NSRect, color: NSColor, turnedOn flag: Bool) { print("drawInsertionPoint", flag) } } ``
Topic: UI Frameworks SubTopic: AppKit Tags:
3
0
60
Apr ’25
Get NSTextView selection frame with NSTextLayoutManager
I'm trying to update my app to use TextKit 2. The one thing that I'm still not sure about is how I can get the selection frame. My app uses it to auto-scroll the text to keep the cursor at the same height when the text wraps onto a new line or a newline is manually inserted. Currently I'm using NSLayoutManager.layoutManager!.boundingRect(forGlyphRange:in:). The code below almost works. When editing the text or changing the selection, the current selection frame is printed out. My expectation is that the selection frame after a text or selection change should be equal to the selection frame before the next text change. I've noticed that this is not always true when the text has a NSParagraphStyle with spacing > 0. As long as I type at the end of the text, everything's fine, but if I insert some lines, then move the selection somewhere into the middle of the text and insert another newline, the frame printed after manually moving the selection is different than the frame before the newline is inserted. It seems that the offset between the two frames is exactly the same as the paragraph style's spacing. Instead when moving the selection with the arrow key the printed frames are correct. I've filed FB17104954. class ViewController: NSViewController, NSTextViewDelegate { private var textView: NSTextView! override func loadView() { let scrollView = NSScrollView(frame: CGRect(x: 0, y: 0, width: 400, height: 400)) textView = NSTextView(frame: scrollView.frame) textView.autoresizingMask = [.width, .height] textView.delegate = self let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = 40 textView.typingAttributes = [.foregroundColor: NSColor.labelColor, .paragraphStyle: paragraphStyle] scrollView.documentView = textView scrollView.hasVerticalScroller = true view = scrollView } func textView(_ textView: NSTextView, shouldChangeTextIn affectedCharRange: NSRange, replacementString: String?) -> Bool { print("before", selectionFrame.maxY, selectionFrame) return true } func textDidChange(_ notification: Notification) { print("after ", selectionFrame.maxY, selectionFrame) } func textViewDidChangeSelection(_ notification: Notification) { print("select", selectionFrame.maxY, selectionFrame) } var selectionFrame: CGRect { guard let selection = textView.textLayoutManager!.textSelections.first?.textRanges.first else { return .null } var frame = CGRect.null textView.textLayoutManager!.ensureLayout(for: selection) textView.textLayoutManager!.enumerateTextSegments(in: selection, type: .selection, options: [.rangeNotRequired]) { _, rect, _, _ in frame = rect return false } return frame } }
0
1
62
Apr ’25
Save fails after Save As
I have an app with two file types with the following extensions: gop (an exported type), sgf (an imported type). The Save command fails after the following sequence of events: I open a gop file, say the file "A.gop". I save this file as an sgf file, say "A.sgf". This Save As works perfectly and the document name in the document’s title bar has changed to "A.sgf". I change something in the document and then try to Save this change. This should just resave the document to "A.sgf", but "A.sgf" remains untouched. Instead I get a system alert with the message The document “A.sgf” could not be saved. A file with the name “A.gop” already exists. To save the file, either provide a different name, or move aside or delete the existing file, and try again. In the Xcode console I get the following diagnostic: NSFileSandboxingRequestRelatedItemExtension: an error was received from pboxd instead of a token. Domain: NSPOSIXErrorDomain, code: 2 [NSFileCoordinator itemAtURL:willMoveToURL:] could not get a sandbox extension. oldURL: file:///Users/francois/Desktop/A.sgf, newURL: file:///Users/francois/Desktop/A.gop The problem seems to relate to the sandbox. But I am at a loss to find a solution. (After closing the alert, I check that A.sgf did not register the change.) If I open an sgf file, say "B.sgf", save it as "B.gop", make a change in the document and then try to save this change (into "B.gop"), I hit the same problem, with "gop" and "sgf" interchanged. If, instead of saving "A.gop" as "A.sgf", I save it as "B.sgf", make a change in the document and then try to save this change into "B.sgf", I get the following system alert: The document “B.sgf” could not be saved. You don’t have permission. To view or change permissions, select the item in the Finder and choose File > Get Info. And in the Xcode console I get the following diagnostic: NSFileSandboxingRequestRelatedItemExtension: an error was received from pboxd instead of a token. Domain: NSPOSIXErrorDomain, code: 2 [NSFileCoordinator itemAtURL:willMoveToURL:] could not get a sandbox extension. oldURL: file:///Users/francois/Desktop/B.sgf, newURL: file:///Users/francois/Desktop/B.gop Again the sandbox ! (After closing the alert, I check that B.sgf did not register the change.) It’s clear my code is missing something, but what?
0
0
60
Apr ’25
NSToolbar doesn't restore displayMode when NSWindow.titleVisibility = .hidden
Apparently when setting a window to hide its title, the toolbar's displayMode is not restored when relaunching the app. For example, by default my app sets to show toolbar icons only, but when right-clicking it, selecting "Icon and Text" and relaunching the app, it's again "Icon Only". Is there a workaround? I've filed FB17144212. class ViewController: NSViewController, NSToolbarDelegate { override func viewDidAppear() { let toolbar = NSToolbar(identifier: "toolbar") toolbar.delegate = self toolbar.autosavesConfiguration = true toolbar.displayMode = .iconOnly view.window?.titleVisibility = .hidden view.window?.toolbar = toolbar view.window?.toolbarStyle = .unified } func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { return [.init(rawValue: "item")] } func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { return [.init(rawValue: "item")] } func toolbar(_ toolbar: NSToolbar, itemForItemIdentifier itemIdentifier: NSToolbarItem.Identifier, willBeInsertedIntoToolbar flag: Bool) -> NSToolbarItem? { let item = NSToolbarItem(itemIdentifier: itemIdentifier) item.image = NSImage(named: NSImage.addTemplateName)! item.label = "item" return item } }
Topic: UI Frameworks SubTopic: AppKit Tags:
1
0
46
Apr ’25
Handle double click on a file associated with my application
When my application starts up I want to check if the application starts because of double click in Finder, or open file in Finder. If the file is opened from Finder I will not show Welcome screen and open directly the file. But if there is no such file it will show Welcome screen. I can register for kAEOpenDocuments but I had to wait for the event to be triggered and how long should I wait. What would be the proper way to handle this
1
0
42
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
92
Apr ’25
📍 Inconsistent POI Visibility Between Apple Maps and MKLocalSearch / CLGeocoder
Summary: Hi! I'm experiencing an issue between what Apple Maps displays in the UI and what is accessible via MapKit APIs such as MKLocalSearch and CLGeocoder. Specifically, some verified and publicly visible businesses (with proper POI categories like .cafe) are not returned by coordinate-based POI searches or reverse geocoding, even when their exact address and coordinates are known. Repro Steps: In Apple Maps (iOS), search for Rustic Knead located at: 1130 State St, Lemont, IL 60439 Note that: The business appears visually on the map It is categorized as a cafe The address is 1130 State St Now in code, attempt both: A coordinate-based POI search using MKLocalSearch.Request(region:) A reverse geocoding lookup via CLGeocoder.reverseGeocodeLocation Example coordinates: latitude: 41.673604, longitude: -88.002295 Expected Behavior: Given the precise coordinates and Apple Maps showing the POI publicly, I expect either or both of the following: MKLocalSearch should return the POI (Rustic Knead) within a reasonable radius and appropriate .pointOfInterestFilter. CLGeocoder should return a CLPlacemark with either name = "Rustic Knead" or an areasOfInterest value containing it. Actual Behavior: MKLocalSearch returns 0 POIs at that location, even with filters removed and radius increased to 500+ meters. CLGeocoder.reverseGeocodeLocation returns a valid postal address but does not include the business name in .name or areasOfInterest. Searching by business name (e.g., "Rustic Knead") does work, but coordinate/address-only lookups do not. Questions: Are there known limitations in how MapKit surfaces POIs by coordinate or reverse geocode? Is there a way to ensure public, categorized POIs are accessible programmatically via MapKit APIs? Is there a better strategy to provide coordinates and return a business name?
1
0
45
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
55
Apr ’25
NSOpenPanel fails with NSUserDefaults domain 'nil' under SDL2 with macOS Sequoia . SDL2 C++
This is with SDL2 and C++ Due to the new security design of Sequoia involving the sandboxed helper processes (via ViewBridge) to show open/save panels, my existing code for invoking Open/SaveAs/FolderSelect dialogs no longer works and instead terminates with ViewBridge Code=14 "(null)" error. Even in the simplest of forms such as; nfdresult_t NFD_OpenDialogN_With_Impl(nfdversion_t version, nfdnchar_t** outPath, const nfdopendialognargs_t* args) { nfdresult_t result = NFD_CANCEL; NSOpenPanel* dialog = [NSOpenPanel openPanel]; if ([dialog runModal] == NSModalResponseOK) { result = NFD_OKAY; } return result; } ...Will no longer work. My Question is essentially, how can I resolve this NSUserDefaults domain empty/nil issue ( currently I don't pass anything for sharing defaults during the process ). Dump of fault provided in crash.txt ( the program doesn't actually crash, it just doesn't invoke the file-open dialog ) crash.txt
1
1
137
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
63
Apr ’25
macOS: First Hangul input ignored/separated after locale change or initial focus with default Korean IME
I reported Korean IME bug to QT Bug report. Please refer to below link. https://bugreports.qt.io/browse/QTBUG-136128?jql=text%20~%20korean%20ORDER%20BY%20created%20DESC But, QT reponsed me like follwing. Thank you for reporting. However, this issue seems like a known issue with apple's Korean IME. There are many threads in Korean community about the same problem with Non-Qt apps. If this issue is a really Qt issue, feel free to open it again. Is there any workaround to fix this IME bug ? Thanks, Ted
0
0
70
May ’25
Getting the content of an NSView in an NSImage in OSX15 sequoia
as all the nice system services that were CGWindowListCreateImage, lockFocus are now deprecated, and drastic restictions are imposed to CALayer/renderInContext:, i just cant figure out how to design a single generic obj C method to capture the content of an NSView , whatever this view is ( subclassed or not, layer backed of not ). As simple as that. this was the method, which now no longer works : //============================================================================= +(NSImage*) viewImageShot:(NSView*)view :(BOOL)bFlip //============================================================================= // capture an NSImage of the given view content // pass window.contentView to capture the whole window,cropping the title bar { CGFloat wantedLayer = view.wantsLayer; BOOL wasHidden= view.hidden; view.hidden= NO; view.wantsLayer= YES; NSImage *requiredImage = [[NSImage alloc] initWithSize:view.bounds.size]; [requiredImage lockFocus]; CGContextRef context= [[NSGraphicsContext currentContext] CGContext]; if(bFlip) FlipContext(context, view.bounds.size.height); [view.layer renderInContext:context]; [requiredImage unlockFocus]; view.wantsLayer = wantedLayer; view.hidden = wasHidden; return requiredImage; } Is there here some hope to get some help or direction to acheive this goal ? thanks to those whow will answer.
Topic: UI Frameworks SubTopic: AppKit
1
0
57
May ’25
NSTableView batch update issue
I create a simple list, there are two kind of item: conversation and message, if click a conversation, it will expand it's messages. So there will be some insert and remove updates. I calculate the difference results and perform the batch update. displayItems = newDisplayItems tableView.beginUpdates() tableView.removeRows(at: IndexSet(removeIndex), withAnimation: [.effectFade, .slideUp]) tableView.insertRows(at: IndexSet(insertIndex), withAnimation: [.effectFade, .slideDown]) tableView.endUpdates() In most cases, the animation looks fine, but when the mock data is large (> 1000?) and called scrollRowToVisible to scroll to the last row in viewDidAppear, then click some conversations above, the UI broken. Is there something wrong? Would appreciate help from someone experienced with NSTableView. Example code
Topic: UI Frameworks SubTopic: AppKit
2
0
39
May ’25
memory leak upon mouse down in a NSTextField
Dear all, Sorry if the topic has already been commented but I could not be able to find it in over 10,000 picks using the forum search field... My problem is that with any NSTextField in my app, a click will result in a memory leak. There is no code attached, just bindings to NSNumber properties. How can I fix this ? Thanks for your help. Best regards Chris
Topic: UI Frameworks SubTopic: AppKit
0
0
47
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
65
May ’25
Room Plan Issue (structure.capturedStructure)
Hi everyone, My app crashed when using the merge room feature. I suspect the issue might be caused by a wall having more than 4 edges. Has anyone experienced a similar problem and found a solution? I’d really appreciate any advice or suggestions. Thank you all, and have a great day! let capturedStructure = try await structure.capturedStructure(from: self.rooms)
1
1
75
May ’25
Crash in IndexSet.map during menu item validation in client report downloaded by Xcode
For many years I've had the following code to access the active objects of a table view in my App Store app: class MyViewController: NSViewController: NSMenuItemValidation { private var tableView: NSTableView! private var objects = [MyObject]() func numberOfRows(in tableView: NSTableView) -> Int { return objects.count } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { // make view for row } private var activeObjects: [MyObject] { return tableView?.activeRowIndexes.map({ objects[$0] }) ?? [] } func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { let activeObjects = self.activeObjects ... } } extension NSTableView { var activeRowIndexes: IndexSet { return clickedRow == -1 || selectedRowIndexes.contains(clickedRow) ? selectedRowIndexes : IndexSet(integer: clickedRow) } } In one of the recent updates, I wanted to add some kind of header to the table view, so I decided to add a row at the beginning and offset the indexes by 1. func numberOfRows(in tableView: NSTableView) -> Int { return objects.count + 1 } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { if row == 0 { // make header view } else { // make view for row - 1 } } private var activeObjects: [MyObject] { return tableView?.activeRowIndexes.subtracting(IndexSet(integer: 0)).map({ objects[$0 - 1] }) ?? [] } But since I added this change, Xcode regularly downloads crash reports from clients crashing during menu item validation in IndexSet.map with reason Code 5 Trace/BPT trap: 5. I assumed that I was accessing an invalid array index, so I added some debug code: the crash report would then show the invalid index beside the crashed thread's name. private var activeObjects: [MyObject] { return tableView?.activeRowIndexes.subtracting(IndexSet(integer: 0)).map({ i in if !objects.indices.contains(i - 1) { Thread.current.name = (Thread.current.name ?? "") + ". Invalid index \(i - 1) for count \(objects.count)" preconditionFailure() } return objects[i - 1] }) ?? [] } But the crash reports for this new app version look just like the old ones and the thread name is not changed. Indeed, when recreating an invalid index access on my Mac, the crash report mentions Array._checkSubscript(_:wasNativeTypeChecked:), which does not appear in the crash reports downloaded by Xcode. Manually symbolicating the crash report also doesn't give any more information: all lines referring to my app code are resolved to either /<compiler-generated>:0 or MyViewController.swift:0. Apparently the problem is not an invalid array index, but something else. Does anybody have a clue what the problem could be? (Note: the crash report mentions Sequence.compactMap because now I'm effectively calling tableView?.activeRowIndexes.compactMap, but the same crash happened before when calling IndexSet.map, which would appear in the crash report as Collection.map.) crash2.crash
3
0
64
May ’25
NSLayoutManager Bug -- layout manager re-laying out overlapping text into the same container.
I've posted a couple times now about major issues I'm having with NSLayoutManager and have written to Apple for code-level support, but no one at Apple has responded to me in more than two weeks. So I'm turning to the community again for any help whatsoever. I'm fairly certain it's a real bug in TextKit. If I'm right about that, I'd love for anyone at Apple to take an interest. And better yet, if I'm wrong (and I hope I am), I'd be incredibly grateful to anyone who can point out where my mistake lies! I've been stuck with this bug for weeks on end. The crux of the issue is that I'm getting what seemed to be totally incompatible results from back to back calls to textContainer(forGlyphAt:effectiveRange:) and lineFragmentRect(forGlyphAt:effectiveRange:withoutAdditionalLayout:)... I'd lay out my text into a fairly tall container of standard page width and then query the layout manager for the text container and line fragment rect for a particular glyph (a glyph that happens to fall after many newlines). Impossibly, the layout manager would report that that glyph was in said very tall container, but that the maxY of its lineFragmentRect was only at 14 points (my NSTextView's isFlipped is true, so that's 14 points measuring from the top down). After investigating, it appears that what is happening under the hood is NSLayoutManager is for some reason laying out text back into the first container in my series of containers, rather than overflowing it into the next container(s) and/or giving me a nil result for textContainer(forGlyphAt:...) I've created a totally stripped down version of my project that recreates this issue reliably and I'm hoping literally anyone at Apple will respond to me. In order to recreate the bug, I've had to build a very specific set of preview data - namely some NSTextStorage content and a unique set of NSTextViews / NSTextContainers. Because of the unique and particular setup required to recreate this bug, the code is too much to paste here (my preview data definition is a little unwieldy but the code that actually processes/parses it is not). I can share the project if anyone is able and willing to look into this with me. It seems I'm not able to share a .zip of the project folder here but am happy to email or share a dropbox link.
7
0
132
May ’25
Is applicationDidFinishLaunching: guaranteed to be called before INIntent delegate methods when app is launched via a Shortcut?
I have a question about the app lifecycle when my app is launched via a Shortcut. I'm adding a INIntent to a Mac app. So my app delegate implements: - (nullable id)application:(NSApplication *)application handlerForIntent:(INIntent *)intent Then my custom intent handler implements the two protocol methods -confirmIntentNameHere:completion: and -handleIntentNameHere:completion: During my testing -applicationDidFinishLaunching: is called before the intent methods, so I can forward methods to my main window controller to perform the shortcut actions, since it's already ready. ....But if this is not always the case, I can still perform them but I'd have to move the code out of the window controller to perform the action "headless" if invoked before my app has built its UI. Just wondering if this is something I should be prepared for. Thanks in advance.
1
0
80
May ’25
NSPredicateEditorRowTemplate subviews layout
Hello everyone, I’d appreciate if anyone can tell me if there’s a way to actually control visual layout of subviews in a predicate editor row template. I have a predicate editor with custom row template subclasses, all created in code (not in IB) and it all works fine, but the problem are template (sub)views, which are not NSPopUpButton(s). As I select different items of popup buttons, effectively changing editor’s predicate property, those buttons seem to get resized according to some strange own logic, but the general the problem is that size (width) of controls, such are text fields and date pickers, gets unpredictable and they usually shrink, even though there is still a plenty of room in the template row width. Trying to resize any control in a row template by force (setFrame: or setFrameSize:) has no effect. I can show some screenshots and videos of the behaviour, as well as code samples, if necessary, but I’d like to ask first, maybe someone already knows what I’m talking about and provide some insights and solutions. Thanks in advance.
Topic: UI Frameworks SubTopic: AppKit
0
0
40
May ’25