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

AppKit Documentation

Post

Replies

Boosts

Views

Activity

Progress bar in NSTableCellView changes to other cell when scrolling
Hello, I'm not I00% sure how to ask this, so I apologize if I word it wrong. This is Obj-C from an older project I have. My app has a NSTableView and each cell has a button to perform and action and shows a progress bar in each cell. The issue I'm running in to is when I scroll down while a task is running the running progress bar shows running on a different cell. So if its he 2nd from the bottom and a scroll an even number of row its equivalent is now showing the progress bar. How do I target just that one cell; making it unique?
1
0
97
5d
Attachment is displayed incorrectly
In the recent MacOS Sequoia Beta 3 NSTextAttachment initialized with custom data and an Image cell as attachmentCell are shown as a file icon istead of the image cell. I am creating a NSAttributedString and showing it in NSTextView like this: NSTextAttachment *attachment = [[NSTextAttachment alloc] initWithData:[text dataUsingEncoding:NSUTF8StringEncoding] ofType:nil]; attachment.attachmentCell = [[NSTextAttachmentCell alloc] initImageCell:img]; NSMutableAttributedString *res = [[NSMutableAttributedString alloc] initWithAttributedString:[NSAttributedString attributedStringWithAttachment:attachment]]; ...
0
0
114
6d
How to capture or monitor all kind of keyboard event from NSViewController?
import Cocoa class MyView: NSView { override init(frame frameRect: NSRect) { super.init(frame: frameRect) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func becomeFirstResponder() -> Bool { return true } override var acceptsFirstResponder: Bool { return true } override func keyUp(with event: NSEvent) { print("keyUp: keyCode=\(event.keyCode)") } // the 'CMD + q' combination will quit the app // the 'CMD + t' combination will open a font setting window // the 'CMD + Space' combination will toggle the spotlight search // the 'CTRL + Space' combination will toggle the input method switching // why this can't capture the key board event like 'CMD + Space' or 'CMD + t' or 'CMD + q'? // or how capture those combinations regardless of the system-wide shortcuts? override func keyDown(with event: NSEvent) { print("keyDown: keyCode=\(event.keyCode)") if event.modifierFlags.contains(.command) { if event.keyCode == 49 { print("keyDown: CMD + Space") // if the 'CMD' and 'Space' keys were pressed both, this line is not print } else { print("keyDown: CMD + others") // here, like 'CMD' and 'j' keys were pressed both, this line is print } } else if event.modifierFlags.contains(.control) { if event.keyCode == 49 { print("keyDown: CTRL + Space") // if the 'CTRL' and 'Space' keys were pressed both, this line is not print } else { print("keyDown: CTRL + others") // here, like 'CTRL' and 'j' keys were pressed both, this line is print } } else { print("keyDown: CMD or CTRL is not pressed") } } override func flagsChanged(with event: NSEvent) { print(#function, event.keyCode) } } class ViewController: NSViewController { override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear() { super.viewWillAppear() let myview = MyView(frame: view.bounds) view.addSubview(myview) } }
3
0
153
1w
SF Symbol rotate animation in NSImageView looks weird in macOS 15 beta
When using the new ‘addSymbolEffect’ effect method on NSImageView with the ‘.rotate.byLayer’ parameter with an applicable SF Symbol 6 symbol, the resulting animation is not completely as expected, to say it mildly. This is the code line I use: imageView.addSymbolEffect(.rotate.byLayer, options: .repeat(.continuous), animated: true) The correct layer rotates around the correct anchor point, but the whole image is moving up and down. The same code with the same symbol in iOS 18 beta runs perfectly. Does anyone know how to get this new rotate API correctly working in macOS 15 beta? In case an Apple engineer reads this: FB13916874 contains example projects for macOS (wobbling rotation) and iOS (perfect rotation), and a screen recording what I see in macOS 15 beta.
0
0
129
1w
Regression macOS 15 beta: NSTableViewDiffableDataSource does not call the 'cellProvider' when the data of a visible cell changes
In one of my apps, I use NSTableViewDiffableDataSource in tandem with NSFetchedResultsController, which provides the necessary snapshots. This works great in macOS 14.5. However in latest macOS 15 betas, NSTableViewDiffableDataSource does not call the 'cellProvider' completion handler anymore when the data of a visible cell changes. When data of a visible cell changes, the didChangeContentWith method of NSFetchedResultsController is called correctly, but applying the provided snapshot doesn’t result in calling the said 'cellProvider' completion handler. This looks a rollback to the early state of this API in 2020. It concerns this piece of code: dataSource = NSTableViewDiffableDataSource(tableView: tableView, cellProvider: { (tableView, tableColumn, row, item) -> NSView in // Return a cell view with data }) Does anyone know a solution or workaround to get animated updates of visible cells working in macOS 15 beta? Yes, applying the snapshot without animation works, but that’s not where NSTableViewDiffableDataSource is designed for. In case an Apple engineer reads this: Looking at the sample code associated with FB13931189, is there anything wrongly implemented that prevents calling the 'cellProvider' method for visible cells? Is this perhaps actually a bug of NSFetchedResultsController? I’m asking this because NSCollectionViewDiffableDataSource does have a very similar problem (FB13943853). PS Yes, this post looks very similar to https://developer.apple.com/forums/thread/759381#759381021, because the problem is identical except that concerns NSCollectionViewDiffableDataSource.
0
0
138
1w
Regression macOS 15 beta: NSCollectionViewDiffableDataSource does not call the 'itemProvider' when the data of a visible item changes
In one of my apps, I use NSCollectionViewDiffableDataSource in tandem with NSFetchedResultsController, which provides the necessary snapshots. This works great in macOS 14.5. However, when updating data in Core Data related to a visible item in a NSCollectionView, the NSCollectionViewDiffableDataSource no longer calls the ‘itemProvider’ closure of the diffable data source when using macOS 15 Seed 3, after applying a snapshot with animation. As a result of this, the collection view does not update visible items when the related data changes. I’m talking about this piece of code which is no longer called when it concerns a visible item: dataSource = NSCollectionViewDiffableDataSource<String, NSManagedObjectID>(collectionView: collectionView, itemProvider: { // Return an NSCollectionViewItem here }) Does anyone know a workaround or solution to get updating of visible cells working in macOS 15 Seed 3, without losing animated updates? In case an Apple engineer is reading this: Are there any related API changes that must be taken into account? Is this perhaps actually a bug of NSFetchedResultsController? I’m asking this because NSTableViewDiffableDataSource does have a very similar problem in macOS 15 beta. See also FB13943853
0
0
129
1w
NSApplicationPresentationDisableHideApplication is not disabling the "Hide" option from the dock menu
Hello, I am trying to use the following code to disable the Hide option for my application : NSApplicationPresentationOptions options = [NSApp presentationOptions]; options |= NSApplicationPresentationDisableHideApplication; [NSApp setPresentationOptions:options]; , but it doesn't have any effect : the Hide option is still clickable : How could I remove this option? Thanks for any help in advance!
0
0
109
1w
refresh the folder icon
Problem Description: I used Swift code to change a folder icon by calling the NSWorkspace.shared.setIcon(_:forFile:options:) method. The specific code is as follows: NSWorkspace.shared.setIcon(coloredIcon, forFile: folderURL.path, options: [.exclude10_4ElementsIconCreationOption]) I noticed that the folder icon has been correctly changed in the Finder preview window, but the icon displayed on the desktop is still the original one. Expected Result: I hope the folder icon on the desktop can also be updated to display the new icon. Solutions Tried: I have tried restarting Finder and manually refreshing the icon cache, but the folder icon on the desktop still does not update. Help Needed: I would like to know if there is a way to automatically refresh the desktop folder icon cache in Swift code to ensure that the changed icon can be immediately displayed.
0
0
149
2w
I tried to add a overlay window onto app in full screen mode but failed
As the topic mentioned, I want to add a overlay window onto Apps that are in full screen mode, trying to create some blur effect on the screen. But Apple seems to treat full screen mode Apps differently as a "space." So currently I can only apply the blur effect like this. (This is my Desktop page) But When it doesn't affect the full screen mode Apps. (For example: My Xcode) And I know some of the App down this kind of stuff. Like this This is my current code. Hope someone can tell me how to solve it.
1
0
245
2w
Display interactable UI on macOS login screen
We are developing a lightweight VPN client inside a daemon process that will run even when no user session is active on machine. The lightweight VPN runs in machine context and does not require user session. We would like to display some basic diagnosis information about our lightweight client on macOS login window before user is logged into their machine (in case users need that). So, is it possible to display a UI window on login screen with some basic info that user can interact with. If yes, where can I get started? Please note, this is not an authorization plugin. We are just wanting to display info about our process that runs a lightweight VPN client on macOS login screen.
0
0
178
2w
Programmatically created NSWindow crashes upon close
I am trying to wrap my head around proper lifecycles of NSWindows and how to handle them properly. I have the default macOS app template with a ViewController inside a window that is inside a Window Controller. I also create a simple programatic window in applicationDidFinishLaunching like this: let dummyWindow = CustomWindow(contentRect: .init(origin: .zero, size: .init(width: 200, height: 100)), styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: true) dummyWindow.title = "Code window" dummyWindow.makeKeyAndOrderFront(nil) The CustomWindow class is just: class CustomWindow: NSWindow { deinit { print("Deinitializing window...") } } When I close the programatic window (either by calling .close() or by just tapping the red close button, the app crashes with EXC_BAD_ACCESS. Even though I am not accessing the window in any way. One might think it's because of ARC but it's not. One—the window is still strongly referenced by NSApplication.shared.windows even when the local scope of applicationDidFinishLaunching ends. And two—the "Deinitializing window..." is only printed after the window is closed. Closing the Interface Builder window works without any crashes. I dug deep and played with the isReleasedWhenClosed property. It made no difference whether it was false or true for the IB window. It stopped the crashing for the programmatic window though. But this raises three questions: What is accessing the programatic window after it's closed—causing a crash because the default behaviour of NSWindow is to release it—if it's not my code? What is the difference under the hood between a normal window and a window inside a window controller that prevents these crashes? If the recommended approach for programmatic windows is to always set isReleasedWhenClosed = true then how do you actually release a programatic window so that it does not linger in memory indefinetely? If the EXC_BAD_ACCESS means that an object is double de-allocated then that would mean that .close() both releases the window (first release) and removes it from the window list which would mean last strong reference is released and ARC cleans the window out (second release). The theory is supported by me calling .orderOut() instead of close which only removes it from the application list and that does indeed release it without crash. Does this mean programmatic windows should override the close() instance method to call orderOut() instead? This seems like poor API design or I am understanding it wrong?
2
0
226
3w
NSTableView flickers while using dynamic cell heights in macOS Sonoma
Suppose we have a nstableview(view based) with automatic row heights enabled. Also each cell view is very dynamic with a lot of elements including text views, buttons and custom views. The enclosingScrollView for the tableview has vertical elasticity. In this case, there is flicker occurring when we pull down or pull up in the tableview. The more dynamic the cells are the greater the amount of flicker. I suspect this would be the cause, Since this did not occur when building with xcode 14 macOS Ventura, There are some changes that have been said to be made in WWDC 2023 regarding automatic row heights in macOS Sonoma - https://developer.apple.com/videos/play/wwdc2023/10054/ Kindly suggest fixes or alternative ways to achieve smoother performance.
0
0
133
3w
NSTextInputClient concurrency issues in Swift 6
Hello! In our codebase we have a NSView subclass that conforms to NSTextInputClient. This protocol is currently not marked as a main actor, but in the decade this has been in use here it has always been called on the main thread from AppKit. With Swift 6 (or complete concurrency checking in Swift 5) this conformance causes issues since NSView is a main actor but not this protocol. I've tried a few of the usual fixes (MainActor.assumeIsolated or prefixing the protocol conformance with @preconcurrency) but they were not able to resolve all warnings. So I dug in the AppKit headers and found that NSTextInputClient is usually implemented by the view itself, but that that is not a hard requirement (see NSTextInputContext.h the documentation for the client property or here). With that I turned my NSView subclass extension into a separate class that is not a main actor and in my NSView subclass create an instance of it and NSTextInputContext. This all seems to work fine in my initial tests, the delegate methods are called. But when the window loses and then regains key, I see a warning message in the console output. -[TUINSCursorUIController activate:]: Foo.TextInputClient isn't subclass of NSView. So my question is, am I doing it wrong with the custom class that implements the protocol? Or is the warning wrong? I would also appreciate a hint on how to better resolve the concurrency issues with NSTextInputClient. Is a main actor annotation coming at some point from your end? Thanks! Markus
0
1
209
3w
NSTableView cells disappear on macOS Sonoma
Hi, i have an old popover status bar mac app that i didn't check in the past few macOS releases, so don't know when the problem appeared. On Sonoma i have the following problem: All NSTableViews cells when they are reused the second time, they are blank. The cells are of type view and only one column. If i investigate in the Xcode's view hierarchy I indeed see no subviews in the cell, but if i print the subviews and their frames and their visibility, they are there alright, they exist. All the cells are instantiated from nib and I tried few strategies to use them: register the cell in the tableview and load it with tableView.makeView(withIdentifier: ) no registration, just load them from xib and keep a reference to their instance and feed that to the table when asked no registration, load them from xib when the table asks. This solution actually works but i really need a reference to them that doesn't change, it's a settings screen and someone else is feeding some info to this cells. I'm stuck, I have no idea what is happening, can you think of something? Thanks!
0
0
210
Jun ’24
Opt out of window tiling (macOS 15)
Is there a way to opt certain windows out of tiling in macOS 15? I'm supporting a beloved feature called App Veil[1], which places windows below others that are not owned by the host application. These windows are passive: they don't allow mouse events and cannot be resized or moved. With the new tiling feature on macOS 15, the window manager will rearrange these windows if you choose an arrangement option (such as Arrange Left & Right). Ideally, I'd like to opt out of this behavior altogether for these windows, but I couldn't find a way to do that. The only thing I've found was that I could set a high window level, but that's not really an option as it's important to preserve the ordering so that the windows are directly below the out-of-process windows. 1: https://tuple.app/app-veil
0
0
243
Jun ’24
Delete button in default NSSavePanel for new document
I just noticed that when closing a new document with edits in MacOS Sonoma that it skips the Save/Don't Save/Cancel panel and goes directly to default NSSavePanel with Delete/Cancel/Save buttons. The problem is that when I click "Delete" nothing happens. It should have simple solution, but I could not find anything. How does one respond to the "Delete" button? My undocumented (as far as I can tell) hack was to implement document:didSave:contextinfo selector for runModalSavePanelForSaveOperation. It appears that in this method for a new document: Delete button has didSave=YES (even though it did not save) and the document fileURL nil Cancel button has didSave=NO and document fileURL nil Save button has didSave=YES and document filieURL to saved file I can handle Delete button this way, but since it is not a documented method, it make me uncomfortable. For example what happens is user clicks "Save", but the save has an error? As an aside, since Apple is now working with ChatGPT, I thought it might provide some help. I asked it how I can respond to "Delete" button in MacOS Sonoma and it said to implement deleteDocument: in your NSDocument subclass. I pointed out to ChatGPT that deleteDocument: does not exist. It said "you are correct" and you should instead check the returned result from runModalSavePanelForSaveOperation and look for "stop" action. I pointed out to ChatGPT that runModalSavePanelForSaveOperation is void and does not return a result, it said again, "you are correct." It gave a third option which basically said to override runModalSavePanelForSaveOperation and build your own save panel from scratch. I didn't know if I should trust this answer. I reverted to my hack and wrote this post. Also ChatGPT never apologized for wasting my time with the wrong answers.
3
0
361
Jun ’24
applicationShouldOpenUntitledFile isn't working anymore
I saw this thread https://forums.developer.apple.com/forums/thread/69888 and I need to not open a new default window just because the app is brought to the front without having any windows open. Unfortunately, that isn't working any more under Sonoma 14.5. Here's my code: // Let's not open default window just because we're being brought to the front. -(BOOL)applicationShouldHandleReopen { return NO; } -(BOOL)applicationShouldOpenUntitledFile { return NO; } I have breakpoints set on both return statements, but they are never hit.
2
0
278
Jun ’24
Crash in AVPlayerView.setPlaybackControlsViewController
A user of my app, which shows subtitles loaded from a text file above a video loaded from another file, reported that it crashes within minutes of launching it. The user confirmed that the crash only happens when they load a video within the app; if they use it without a video, it doesn't crash. The subtitles are shown in a NSTextView added to AVPlayerView.contentOverlayView. What could cause such a crash? I'm not able to reproduce it. (I tried attaching the full crash report but I always got a validation error "This post contains sensitive language. Please revise it in order to continue.") Crashed Thread: 0 Dispatch queue: com.apple.main-thread Exception Type: EXC_BREAKPOINT (SIGTRAP) Exception Codes: 0x0000000000000001, 0x000000019c50cae8 Termination Reason: Namespace SIGNAL, Code 5 Trace/BPT trap: 5 Terminating Process: exc handler [20614] Application Specific Backtrace 0: 0 CoreFoundation 0x0000000198a472ec __exceptionPreprocess + 176 1 libobjc.A.dylib 0x000000019852e788 objc_exception_throw + 60 2 Foundation 0x0000000199b2caa0 -[NSKeyValueNestedProperty object:withObservance:didChangeValueForKeyOrKeys:recurse:forwardingValues:] + 664 3 Foundation 0x0000000199af4e08 -[NSKeyValueUnnestedProperty object:withObservance:didChangeValueForKeyOrKeys:recurse:forwardingValues:] + 196 4 Foundation 0x0000000199b8bc54 NSKeyValueDidChange + 200 5 Foundation 0x0000000199acde1c -[NSObject(NSKeyValueObservingPrivate) _changeValueForKeys:count:maybeOldValuesDict:maybeNewValuesDict:usingBlock:] + 684 6 Foundation 0x0000000199af7484 -[NSObject(NSKeyValueObservingPrivate) _changeValueForKey:key:key:usingBlock:] + 64 7 Foundation 0x0000000199b110e8 _NSSetObjectValueAndNotify + 284 8 AVKit 0x00000001bd3ff694 -[AVPlayerControlsViewController setPlayerController:] + 376 9 Foundation 0x0000000199acddd0 -[NSObject(NSKeyValueObservingPrivate) _changeValueForKeys:count:maybeOldValuesDict:maybeNewValuesDict:usingBlock:] + 608 10 Foundation 0x0000000199af7484 -[NSObject(NSKeyValueObservingPrivate) _changeValueForKey:key:key:usingBlock:] + 64 11 Foundation 0x0000000199b110e8 _NSSetObjectValueAndNotify + 284 12 AVKit 0x00000001bd3c6e68 -[AVPlayerView setPlaybackControlsViewController:] + 88 13 Foundation 0x0000000199b11074 _NSSetObjectValueAndNotify + 168 14 AVKit 0x00000001bd40f4b8 -[AVPlayerView _updatePlaybackControlsViewControllerIfNeeded] + 536 15 AVKit 0x00000001bd3cc0b4 -[AVPlayerView viewDidMoveToWindow] + 136 16 AppKit 0x000000019c24456c -[NSView _setWindow:] + 1788 17 AppKit 0x000000019ccce4a0 __21-[NSView _setWindow:]_block_invoke.146 + 268 18 AppKit 0x000000019c244564 -[NSView _setWindow:] + 1780 19 AppKit 0x000000019ccce4a0 __21-[NSView _setWindow:]_block_invoke.146 + 268 20 AppKit 0x000000019c244564 -[NSView _setWindow:] + 1780 ... 35 AppKit 0x000000019ccce4a0 __21-[NSView _setWindow:]_block_invoke.146 + 268 36 AppKit 0x000000019c244564 -[NSView _setWindow:] + 1780 37 AppKit 0x000000019c428ec0 -[NSWindow dealloc] + 684 38 Foundation 0x000000019a1fa118 _NSKVOPerformWithDeallocatingObservable + 172 39 Foundation 0x0000000199b17404 NSKVODeallocate + 180 40 Foundation 0x0000000199b122f0 empty + 88 41 Foundation 0x0000000199af77fc dealloc + 60 42 Foundation 0x0000000199af7740 -[NSConcreteMapTable dealloc] + 76 43 AppKit 0x000000019c936e80 ___NSTouchBarFinderSetNeedsUpdateOnMain_block_invoke_2 + 1388 44 AppKit 0x000000019c2d4c4c NSDisplayCycleObserverInvoke + 168 45 AppKit 0x000000019c2d48a8 NSDisplayCycleFlush + 644 46 QuartzCore 0x00000001a0bc3f64 _ZN2CA11Transaction19run_commit_handlersE18CATransactionPhase + 120 47 QuartzCore 0x00000001a0bc2d04 _ZN2CA11Transaction6commitEv + 320 48 AppKit 0x000000019c3589d0 __62+[CATransaction(NSCATransaction) NS_setFlushesWithDisplayLink]_block_invoke + 272 49 AppKit 0x000000019cd18208 ___NSRunLoopObserverCreateWithHandler_block_invoke + 64 50 CoreFoundation 0x00000001989d187c __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 36 51 CoreFoundation 0x00000001989d1768 __CFRunLoopDoObservers + 536 52 CoreFoundation 0x00000001989d0d94 __CFRunLoopRun + 776 53 CoreFoundation 0x00000001989d0434 CFRunLoopRunSpecific + 608 54 HIToolbox 0x00000001a317419c RunCurrentEventLoopInMode + 292 55 HIToolbox 0x00000001a3173e2c ReceiveNextEventCommon + 220 ... Thread 0 Crashed:: Dispatch queue: com.apple.main-thread 0 AppKit 0x19c50cae8 -[NSApplication _crashOnException:] + 240 1 AppKit 0x19c358b44 __62+[CATransaction(NSCATransaction) NS_setFlushesWithDisplayLink]_block_invoke + 644 2 AppKit 0x19cd18208 ___NSRunLoopObserverCreateWithHandler_block_invoke + 64 3 CoreFoundation 0x1989d187c __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 36 4 CoreFoundation 0x1989d1768 __CFRunLoopDoObservers + 536 5 CoreFoundation 0x1989d0d94 __CFRunLoopRun + 776 6 CoreFoundation 0x1989d0434 CFRunLoopRunSpecific + 608 7 HIToolbox 0x1a317419c RunCurrentEventLoopInMode + 292 8 HIToolbox 0x1a3173e2c ReceiveNextEventCommon + 220 9 HIToolbox 0x1a3173d30 _BlockUntilNextEventMatchingListInModeWithFilter + 76 10 AppKit 0x19c22fd68 _DPSNextEvent + 660 11 AppKit 0x19ca25808 -[NSApplication(NSEventRouting) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 700 12 AppKit 0x19c22309c -[NSApplication run] + 476 13 AppKit 0x19c1fa2e0 NSApplicationMain + 880 14 Underword 0x102c099ac 0x102c08000 + 6572 15 dyld 0x19856a0e0 start + 2360
2
0
351
Jun ’24