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

AppKit Documentation

Post

Replies

Boosts

Views

Activity

Any way to use a SymbolEffect in an NSButton
Examples of using SymbolEffect in AppKit all seem to be in NSImageView, and look through APIs it seems that the only way to apply those effect animations outside of SwiftUI is indeed in an NSImageView. I have a NSStatusItem where I'm using an SF Symbol in the NSStatusBarButton title (subclass of NSButton) and was trying to figure out if there was a way to use a SymbolEffect there. If the image of an NSButton uses (used) an NSImageView under the hood, that used to hidden in the buttons cell. Seeing how cells seem to be inaccessible now, perhaps there isn't a NSImageView in there these days anyway. Can NSStatusBarButton titles be provided by a custom view, oh I'm guessing the deprecated view property is still operational, but if I'm trying to release to the Mac App Store, that as equally off-limits as an NSButtonCell would have been. Is there a non-deprecated way that will let me ship to the App Store?
1
2
783
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
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
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
notification about change visible window
Hello, I am trying to get a notification about change visible (top) window on Desktop. I am using NSWorkspaceDidActivateApplicationNotification notification and it works fine except situation of minimize current active application. Nothing is posted in notification center if active window is minimized. Are there any way to get some notification about change top window which is currently displayed on Desktop? Thank you in advance for your help!
0
0
377
Feb ’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
NSWindow Suddenly Closes After NSTextField Ends Editing (By Clicking into Another NSTextField)
Configuration: I have a NSTextField (multiline) inside an NSWindow. I have another NSTextField (single line) inside an NSBox (which is in the same window). The multiline text field is first responder and is editing. I click on the single line text field inside the NSBox to edit that one. The NSWindow just closes. This is on Sonoma 14.2.1. I subclassed NSWindow and override the close method and put a breakpoint. Here's the call stack that leads to the window suddenly closing: #1 0x0000000189c73d90 in -[NSWindow __close] () #2 0x000000032343 in -[NSApplication(NSResponder) sendAction:to:from:] () #3 0x0000000189b543ac in -[NSControl sendAction:to:] () #4 0x0000000189b542f0 in __26-[NSCell _sendActionFrom:]_block_invoke () #5 0x0000000189b54218 in -[NSCell _sendActionFrom:] () #6 0x0000000189b5413c in -[NSButtonCell _sendActionFrom:] () #7 0x0000000189c4c508 in __29-[NSButtonCell performClick:]_block_invoke () #8 0x0000000189c4c264 in -[NSButtonCell performClick:] () #9 0x0000000189b545a8 in -[NSApplication(NSResponder) sendAction:to:from:] () #10 0x0000000189b543ac in -[NSControl sendAction:to:] () #11 0x0000000189befb48 in -[NSTextField textDidEndEditing:] () #12 0x0000000__CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ () #13 0x000000018625c65c in ___CFXRegistrationPost_block_invoke () #14 0x000000018625c5a4 in _CFXRegistrationPost () #15 0x00000001861971dc in _CFXNotificationPost () #16 0x0000000187289ff0 in -[NSNotificationCenter postNotificationName:object:userInfo:] () #17 0x0000000189bef754 in -[NSTextView(NSSharing) resignFirstResponder] () #18 0x0000000189a9fab8 in -[NSWindow _realMakeFirstResponder:] () #19 0x0000000189b4f18c in -[NSWindow(NSEventRouting) _handleMouseDownEvent:isDelayedEvent:] () #20 0x0000000189ada79c in -[NSWindow(NSEventRouting) _reallySendEvent:isDelayedEvent:] () #21 0x0000000189ada45c in -[NSWindow(NSEventRouting) sendEvent:] () #22 0x000000018a1879f4 in -[NSApplication(NSEventRouting) sendEvent:] () #23 0x0000000189dd6908 in -[NSApplication _handleEvent:] () #24 0x00000001899a1d74 in -[NSApplication run] () The mouse click is no where near the close button in the title bar.
2
0
581
Feb ’24
monitor input events
Hello, I need to monitor input events and convert keycode to symbol. E.g. convert kHIDUsage_KeyboardQ to symbol according to used keyboard layout. Are there any API to get current keyboard layout (language) in C++? If I understand correctly, the API TISGetInputSourceProperty() is deprecated. Are there any way to monitor keyboard layout changed? (some system notification in case of keyboard layout change) Are there any way to translate keycode to symbol except UCKeyTranslate() which is part of deprecated Unicode Utilities? Thank you in advance.
1
0
583
Feb ’24
NSTextField problem in XCode 15.2
Because my MacOS app has a user-programmable interface, my coding creates lots of interface elements programmatically. Soon after an update to MacOS 14.3.1, I found some of these element (NSTextFields) did not draw correctly. I had not changed any code but the appearance changed for the worse (the text in the text field did not appear). I then noticed: The problem occurs when I compile in XCode 15.2 (15C500b) Version and run on computer with Sonoma 14.3.1 (23D60) If I instead compile in XCode Version 14.1 (14B47b) on Ventura 13.0.1 (22A400) and copy the app to my computer with Sonoma 14.3.1 (23D60)all works as expected. These results seem to imply XCode 15.2 does not compile correctly? Is this known issue or is there a fix?
2
0
739
Feb ’24
Cocoa binding to NSButton messes with enabled state
When an NSButton's value and hidden state are bound to properties, changing either property enables the button. See example code: @interface MyClass () @property (nonatomic) BOOL buttonHidden; @property (nonatomic) BOOL buttonState; @end @implementation MyClass { __weak IBOutlet NSButton *button; // The button is in a view designed in IB } - (void)awakeFromNib { [super awakeFromNib]; [button bind:NSHiddenBinding toObject:self withKeyPath:@"buttonHidden" options:nil]; [button bind:NSValueBinding toObject:self withKeyPath:@"buttonState" options:nil]; button.enabled = NO; self.buttonHidden = NO; // This enables the button. If this line isn't executed, the buttons stays disabled. } @end Note that the issue occurs only of both properties are bound. I wonder if this is by design or a bug.
0
0
417
Feb ’24
NSTextField and NSAttributedString
I'm trying to put an attributed string in to an NSTextField the user creates in their document. I cannot use an NSTextView. The problem is once the textfield is created attributes cannot be edited. Also I work in Objective-c because reasons. So when the field is created this is the code used: [attribDict setObject:[self.editor.delegate foregroundColor] forKey:NSForegroundColorAttributeName]; [attribDict setObject:aFont forKey:NSFontAttributeName]; [attribDict setObject:[self.editor.delegate backgroundColor] forKey:NSBackgroundColorAttributeName]; [attribDict setObject:self.editor.delegate.strokeColor forKey:NSStrokeColorAttributeName]; [attribDict setObject:[NSNumber numberWithInt:-self.editor.delegate.strokeWidth] forKey:NSStrokeWidthAttributeName]; This part works if I set all the attributes before I create the textfield. But I need to be able to edit attributes on the string. For that I use this code: NSFont * aFont = [NSFont fontWithName:self.delegate.fontSelectorButton.title size:self.delegate.fontSize.intValue]; NSMutableDictionary * attribDict = [[NSMutableDictionary alloc]init]; [attribDict setObject:[self.delegate foregroundColor] forKey:NSForegroundColorAttributeName]; [attribDict setObject:aFont forKey:NSFontAttributeName]; [attribDict setObject:[self.delegate backgroundColor] forKey:NSBackgroundColorAttributeName]; [attribDict setObject:self.delegate.strokeColor forKey:NSStrokeColorAttributeName]; [attribDict setObject:[NSNumber numberWithInt:self.delegate.strokeWidth] forKey:NSStrokeWidthAttributeName]; [textShape updateTextAttributesFromDictionary:attribDict]; And finally this is called the change the string attributes: -(void)updateTextAttributesFromDictionary:(NSDictionary*)attribs { self.stringAttributes = attribs; NSMutableAttributedString * as = [[NSMutableAttributedString alloc]initWithAttributedString:self.myTextField.attributedStringValue]; [as beginEditing]; [as setAttributes:attribs range:NSMakeRange(0, as.length)]; [as endEditing]; self.myTextField.attributedStringValue = as; } I have tried just setting the new attributes and get nothing. The above code however gives me wildly unpredictable results. Sometimes the NSTextfield gets a background color that cannot be altered. Sometimes the text vanishes. Sometimes all attributes are lost, sometimes if I include a stroke color and width I get the stroke but no fill. That's the most common. Is there some fundimental NSTextField short coming I'm missing? Is there something I'm missing with NSAttributedString? Are NSAttributedStrings not compatible with NSTextField?
0
0
473
Feb ’24
`NSWorkspace.open` cannot deal with `xcodeproj`
Hello. I could wrong, but it seems NSWorkspace.open cannot open xcodeproj. When I try to do so in my sandboxed App, the App would hang the thread, causing NSWorkspace.open not responsive in the following calls. If called on the @main thread, then bad luck, it would cause dead lock. Callings this function on a normal file, such as .txt, or in a Command line Tool works perfectly. Is there anything obvious that I missed? I have permissions to read/write the files, as indicated by url.resourceValues(forKeys: [.isWritableKey]).isWritable.
1
0
341
Feb ’24
NSMenu.popUp(positioning:at:in:) doesn't enable menu items when opened inside modal window
In my app I use NSMenu.popUp(positioning:at:in:) for displaying a menu in response to the user clicking a button. But it seems that when the menu is opened inside a modal window, all the menu items are always disabled. Using NSMenu.popUpContextMenu(_:with:for:) instead works. What's the reason and what's the difference between the two methods? According to the documentation, one is for opening "popup menus" and the other for opening "context menus", but I cannot see an explanation of the difference between the two. @main class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { let window = NSWindow(contentViewController: ViewController()) NSApp.runModal(for: window) } } class ViewController: NSViewController { override func loadView() { let button = NSButton(title: "Click", target: self, action: #selector(click(_:))) view = NSView(frame: CGRect(x: 0, y: 0, width: 400, height: 400)) view.addSubview(button) } @objc func click(_ sender: Any?) { let menu = NSMenu(title: "") menu.addItem(withTitle: "asdf", action: #selector(asdf(_:)), keyEquivalent: "") menu.addItem(withTitle: "bla", action: nil, keyEquivalent: "") menu.items[0].target = self menu.items[1].target = self // NSMenu.popUpContextMenu(menu, with: NSApp.currentEvent!, for: view) // this works menu.popUp(positioning: nil, at: .zero, in: view) // this doesn't work } @IBAction func asdf(_ sender: Any) { print(0) } }
3
0
603
Feb ’24
Why does `DisclosureGroup` retains object references when content is hidden?
I'm displaying file structure using DisclosureGroup. And I encountered a memory leak problem. Code Node Node represents a file or a folder. isExpanded is used to indicate if the child nodes are visible. If true, it will find its child nodes, which are set into children. If false, it will clear children for releasing references. class Node: ObservableObject, Identifiable, Hashable, CustomStringConvertible { // ... @Published var name: String @Published var children: [Node]? @Published var isExpanded = false { willSet { if self.isFile { // This node represents a file. // It does not have any children. return } if newValue { if children?.count == 0 { DispatchQueue.main.async { // get child nodes self.children = childrenOf(self.url) } } } else { if children?.count != 0 { DispatchQueue.main.async { // collapse child nodes self.children?.forEach { child in child.isExpanded = false } // clear children when this node is collapsed self.children = [] } } } } } init(/*...*/) { // ... print("init \(name)") } deinit { // ... print("deinit \(name)") } // ... } For convenience, I print some messages when initializing Node and deinitializing Node. TreeNode TreeNode displays Node using DisclosureGroup. struct TreeNode: View { @ObservedObject var parent: Node @ObservedObject var node: Node var body: some View { if node.isFile { Text(node.name) } else { DisclosureGroup( isExpanded: $node.isExpanded, content: { if node.isExpanded { ForEach(node.children ?? []) { child in TreeNode(parent: node, node: child) } } }, label: { FolderNodeView(node: node) } ) } } } struct FolderNodeView: View { @ObservedObject var node: Node var body: some View { Label( title: { Text(node.name) }, icon: { Image(systemName: "folder.fill") } ) } } I use if node.isExpanded for lazy loading. When node.isExpanded is true, it will show node's children and print initialization messages. Otherwise, it will hide child nodes and print deinitialization messages. But unexpectedly it does not print any deinitialization messages when the node is collapsed. This indicates that it retains references and therefore these Node objects still exists in memory causing memory leak. Demo When the node is expanded, its child nodes will be displayed after loading is completed. The code works correctly. Then I collapsed the node, it didn't print any deinitialization messages. And when I expanded it again, it initialized new nodes and deinitialized the old nodes at this time. Deinitialization seems to be delayed. So I guess TreeNode retains references when content is hidden. Then I deleted TreeNode in ForEach. DisclosureGroup( isExpanded: $node.isExpanded, content: { if node.isExpanded { ForEach(node.children ?? []) { child in // TreeNode(parent: node, node: child) } } }, label: { FolderNodeView(node: node) } ) It cannot display the child nodes. But it released reference correctly. So the code works expectedly. After that, I tried to replace TreeNode with Text or Label. I found that none of them released references immediately when I collapsed the node. Why did this happen? Any idea how to fix it?
0
0
434
Feb ’24
Developer Program Documentation Access & Xcode
I am new to Apple 🍎 Development 👨‍💻 and Apple 🍎 Developer 👨‍💻 Forums. I have not joined the Apple 🍎 Developer 👨‍💻 Program yet. Is there any documentation 📖 that is only available to paid 💰 Apple 🍎 Developer 👨‍💻 Program members or is all of it freely available to those not (or not yet) in the paid 🚫💰 program? Is Xcode freely downloadable or does it require it be purchased like it used to be for non-program members?
2
0
467
Feb ’24