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

AppKit Documentation

Posts under AppKit tag

232 Posts
Sort by:
Post marked as solved
5 Replies
2.9k Views
Even if the operating system language has been set to something else (such as Finnish), NSError.localizedDescription seems to always have the description in English. I need the error message provided by the system in Finnish, but I have no idea how to achieve this.Somebody on the internets says that in order to achieve this, one has to create a new localization in the Xcode project (which happens on the Info pane of the project settings). I don't need localizations per se, because this project is supposed to be in one single language. Either way, when I try to add a new localization (by clicking on the + button and selecting "Finnish") nothing happens. It shows an empty list of files to localize, and when I click the Finish button, nothing at all happens. No new localization is added to the list.(I'm wondering if this happens because the project has been created in an unconventional manner. More precisely, it has been created by SpriteBuilder. Changing the project to something else is pretty much out of the question, so that's not a solution.)I just want the Finnish version of localizedDescription. How can I retrieve it from the system?
Posted
by
Post not yet marked as solved
6 Replies
5.2k Views
I'm trying to use the Accessibility API and have this code: NSDictionary *options = @{(__bridge id) kAXTrustedCheckOptionPrompt : @YES}; BOOL accessibilityEnabled = AXIsProcessTrustedWithOptions((__bridge CFDictionaryRef) options);This always returns no, however it does not prompt the user for permission nor does it display the app's name in System Preferences > Security & Privacy. What do I need to test this? I could try and add the debug version manually into System Preferences but how do I know that this will work properly when released to the public? Is there any way to test this out? I am not seeing any prompt at all.
Posted
by
Post marked as Apple Recommended
44k Views
I'm having troubles with Paste opertaions into my containers in File Provider extension.If I paste copied image or text into Files app -> My App -> any folder the file at fileURL can not be read (as a result can't be uploaded to my servers nor stored locally).- (void)importDocumentAtURL:(NSURL *)fileURL toParentItemIdentifier:(NSFileProviderItemIdentifier)parentItemIdentifier completionHandler:(void (^)(NSFileProviderItem _Nullable importedDocumentItem, NSError * _Nullable error))completion { NSError *readError = nil; NSData *fileData = [NSData dataWithContentsOfURL:fileURL options:NSDataReadingMappedAlways error:&readError]; NSString *readErrorMessage = readError.localizedDescription; NSURL *myFileURL = [NSFileProviderManager.defaultManager.documentStorageURL URLByAppendingPathComponent:@"temp.dat"]; NSError *copyError = nil; BOOL copyResult = [_fileManager copyItemAtURL:fileURL toURL:myFileURL error:&copyError]; NSString *copyErrorMessage = copyError.localizedDescription; ...copyResult is false, both readErrorMessage and copyErrorMessage are:The file “text.txt” couldn’t be opened because you don’t have permission to view it.What am I doing wrong here?This happens to any file copied from my container, iCloud container, as well as synthetic files produced from text/image/other data from system Clipboard.For emalple, fileURL for image.png file I'm trying to duplicate from my own container isfile:///private/var/mobile/Containers/Data/Application/80480715-574A-4E99-B588-FBDCC7F1FDFC/tmp/DDBD7C7B-56C0-4F61-94A9-109613C78F75/image.png/The same time the item being duplicated is located at:file:///private/var/mobile/Containers/Shared/AppGroup/A8C1416D-8435-407E-82B3-CE10A8439630/File%20Provider%20Storage/Document93838429/image.pngI guess I cant ready anything in /private/var/mobile/Containers/Data/Application/80480715-574A-4E99-B588-FBDCC7F1FDFC/Thanks.
Posted
by
Post not yet marked as solved
2 Replies
2.2k Views
Someone please correct me if I'm mistaken, but I think Apple just deprecated the entire help infrastructure in Mojave.I am doing final testing on a new build of my app. It really bugs me that help anchors don't work. It seemed like I could sometimes get them to work in the past. But now, nothing. It is just a webview, so I decided I would just scrap the whole thing and do it all myself. 2 hours later, that's done. However, I still wanted to use those convenient anchors. I figured I would just call hiutil at runtime to extract the anchors and I would be all done. But hiutil doesn't work on Mojave anymore. It seems seems to create them OK. I can use hiutil to read a helpindex file created on Mojave. But I can't read the same helpindex file on Mojave. I suppose that's irony for you. The one piece of the old help infrastructure that I thought I could salvage in my new version is now broken.Congratulations, Apple! That's the sound of one hand clapping.
Posted
by
Post not yet marked as solved
1 Replies
1.1k Views
I'm using fileImporter for a Mac app. If I open a file from iCloud Drive that isn't already downloaded, I need to start the download before I can read the contents of the file. I found that I can download the file by using NSFileCoordinator or FileManager.default.startDownloadingUbiquitousItem. These APIs will begin the download, but I have no updates on the progress or if the file has been downloaded. I've tried to use NSMetadataQuery with no luck. Is there a way, either with fileImporter in SwiftUI or an AppKit API that I can receive updates for when a remote file has been downloaded, or do I need to prompt the users to download the file themselves before importing into my app?
Posted
by
Post not yet marked as solved
2 Replies
1.7k Views
I'm trying to implement custom NSTextContentManager and use it with NSTextView, however it seems that NSTextView expect NSTextContentStorage all the time. final class MyTextContentManager: NSTextContentManager { // ... } It's added to layout manager, and NSTextView instance finds it properly: let textContentManager = MyTextContentManager() textContentManager.addTextLayoutManager(textLayoutManager) however, when I use it, I see errors at: [MyTextContentManager textStorage]: unrecognized selector sent to instance 0x600003d84870 the textStorage property is part of NSTextStorageObserving, that is not NSTextContentManager interface. It looks like NSTextView is not ready to work with custom NSTextContentManager. What did I miss?
Posted
by
Post not yet marked as solved
3 Replies
747 Views
Using the Lazarus IDE and Free Pascal the following code works in previous macOS versions, but not in Monterey: procedure TForm1.FormActivate(Sender: TObject); begin NSApp := NSApplication.sharedApplication; end; procedure TForm1.Button1Click(Sender: TObject); begin NSApp.dockTile.setBadgeLabel(NSStr('1')); end; Any ideas why it fails in Monterey? There are no related errors in the system console log.
Posted
by
Post not yet marked as solved
2 Replies
1k Views
I am hitting major road blocks in migrating one of my Obj-C-Cocoa applications away from -[NSView (un)lockFocus] and -[NSBitmapImageRep initWithFocusedViewRect:]. In a transcript of a presentation on WWDC2018 I read: With our changes to layer backing, there's a few patterns I want to call out that aren't going to work in macOS 10.14 anymore. If you're using NSView lockFocus and unlockFocus, or trying to access the window's graphics contents directly, there's a better way of doing that. You should just subclass NSView and implement draw rect. ... Of course, we all implemented -[NSView drawRect:] for decades now. The big question is, how can we do incremental (additional, event driven) drawing in our views, without redrawing the whole view hierarchy. This is the use case of -(un)lockFocus, and especially when drawing of the base view is computational expensive. Wo would have thought that people use -(un)lockFocus for regular drawing of the NSView hierarchy. I tried to get away with CALayer, only to find out after two days experimenting with it, that a sublayer can only be drawn if the (expensive) main layer has been drawn before —> dead end road. Now I am going to implement a context dependent -[NSView drawRect:]. Based on a respective instance variable, either of the (expensive) base presentation of the view or the simple additions are drawn. Is it that what Apple meant by … just subclass NSView and implement draw rect? From the point of view of object oriented programming, using switch() in methods to change the behaviour of the object is ugly - to say the least. Any better options? Ugly or not, in any case, I don’t want to redraw the whole view hierarchy only for moving a crosshairs in a diagram. My actual use case is: This application draws into a custom diagram NSView electrochemical measurement curves which may consist of a few thousands up to millions of data points. The diagram view provides a facility for moving crosshairs and other pointing aids over the displayed curves, by dragging/rolling with the mouse or the touch pad, or by moving it point by point with the cursor keys. Diagram generation is computational expensive and it must not occur only because the crosshairs should be moved to the next data point. So for navigating the crosshairs (and other pointing aids), a respective method locks the focus of said view, restores the background from a cache, caches the background below the new position of the crosshairs using -[NSBitmapImageRep initWithFocusedViewRect:], draws the crosshairs and finally unlocks the focus. All this does not work anymore since 10.14.
Posted
by
Post not yet marked as solved
3 Replies
1.2k Views
Hi, Inside a Mac Catalyst app, I need to display a popover starting from an NSToolbarItem contained inside the app toolbar (like the Apple Maps Mac app does, see below image). In order to do that, when I press the button I need to find the toolbar item view and use it as popover anchor. How can I find the view or frame of an NSToolbarItem on Mac Catalyst? A property that could help me is the NSToolbarItem "view" property (NSView), but that property has been marked has unavailable in Mac Catalyst. Any idea? Thank you
Posted
by
Post not yet marked as solved
1 Replies
982 Views
System Version: macOS Monterey 12.3.1 My app has a button which will show popover when clicked the button and make a button in the popover to be the popover's window's firstResponder. When Voiceover is not on, I am able to close the popover using escape key (handled by NSpopover's contentView). But when I turned voice over on, pressing escape key cause both the popover and its parent window to escape, and the debug result showed that the popover's sender received the key event rather the popover (In sender's window pressing escape will close the window). This problem disappeared when I changed the popover's behavior to .applicationDefined (still not working for .transient or .semitransient), but I still want to know why VoiceOver will affect the behavior of NSpopover
Posted
by
Post not yet marked as solved
3 Replies
1.3k Views
I am facing an odd problem with the global accent color in a macOS application targeting macOS 11 +. The color is defined in an asset catalog and its name is set as the value of the key Global Accent Color Name in the project's build settings. Despite this, the custom accent color is not applied uniformly throughout the application when the system accent color is set to multicolor. Anywhere where NSColor.controlAccentColor is used explicitly either in code or interface builder, the color is correct. However, wherever the use of the accent color (or its variants) is implicit, the blue system accent color is used instead. This includes the selection in NSMenus, the selected state of NSSegmentedControls, the selection NSOutlineView using the source list style, NSSwitch, NSPopUpButton, NSButton, etc. This problem occurs in both light and dark modes, on macOS 11 and macOS 12. I have compiled the application with Xcode 12.5, and multiple versions Xcode 13. I have found that modifying the system accent color to something other than multicolor and then back to multicolor fixes the problem, but only until the application is quit. At the next launch, the problem reappears.  I have tried all sorts of changes such as: Setting the value directly in info.plist Adding the value in an xconfig file: with the key ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME Forcing views to redraw Renaming the color in the asset catalog Creating a minimal application in an attempt to reproduce the problem. The closest I have come to a solution is investigating in detail the effective appearance of the application, from the property NSApplication.sharedApplication.effectiveAppearance.  The object returned is of the class NSCompositeAppearance. It contains an array of 2 appearances: an NSAquaAppearance or NSDarkAquaAppearance and an NSSystemAppearance.   Two private properties of NSAquaAppearance/NSDarkAquaAppearance are of interest: _tintColor and _cachedNormalizedBezelTintColor. These properties seem to set the color of standard controls. In my problematic application, _tintColor returns the system blue accent color. In other applications without these problems, _tintColor points to the color defined in the asset catalog. _cachedNormalizedBezelTintColor seems derived from _tintColor.  Using key-value coding, I am able to modify these properties and change the appearance of most but not all controls, buttons, and selections. However, I do not want to use private properties and this is just masking the symptom of the real problem. Has anyone experienced this problem with the global accent color? What was the solution?
Posted
by
Post not yet marked as solved
2 Replies
884 Views
Hi, I'm working on making a Document based app for MacOS using AppKit and I wanted the different documents to be displayed as tabs of the same window which after a lot of research I managed to do using this single line: windowController.window?.tabbingMode = .preferred which I added inside the makeWindowControllers function of my Document. I figured that in order to be able to style my tabs I should use this method: windowController.window?.tab.attributedTitle = ... But whatever I added after this = didn't do anything to my tabs. For example I tried this: windowController.window?.tab.attributedTitle = NSAttributedString(string: "Hello", attributes: [NSAttributedString.Key.backgroundColor: NSColor.red]) Weirdly, using this method: windowController.window?.tab.title = ... did work but is far more limited than the other one. Maybe I did something wrong in my implementation of the tabs but it seems to work properly when I run it, only the colors and fonts don't match what I'd like to make which is why I wanted to change them using the attributed title. Here's my full code for the function: override func makeWindowControllers() {     let storyboard = NSStoryboard(name: NSStoryboard.Name("Main"), bundle: nil)     if let windowController =         storyboard.instantiateController(             withIdentifier: NSStoryboard.SceneIdentifier("Document Window Controller")) as? NSWindowController {         addWindowController(windowController)         windowController.window?.tabbingMode = .preferred         windowController.window?.tab.attributedTitle = NSAttributedString(string: "hey", attributes: [NSAttributedString.Key.backgroundColor: NSColor.red])         // Set the view controller's represented object as your document.         if let contentVC = windowController.contentViewController as? ViewController {             contentVC.representedObject = content             contentViewController = contentVC         }     } } I would really appreciate some help on this issue! Thanks by advance, Cyprien
Posted
by
Post not yet marked as solved
1 Replies
748 Views
I was able to implement drag and drop with NSTableViewDiffableDataSource by subclassing and adding the missing methods. It works but the draggingSession willBeginAt method is never called so I can't provided a custom preview to the dragging. Any tips from AppKit developers or Apple engineers? class ListCoordinator: NSTableViewDiffableDataSource<String, Int>, NSTableViewDelegate {     @objc func tableView(_ tableView: NSTableView, pasteboardWriterForRow row: Int) -> NSPasteboardWriting? {         return NSPasteboardItem(pasteboardPropertyList: row.formatted(), ofType: .string)     }     @objc func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation {         return .move     }     @objc func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableView.DropOperation) -> Bool { ...         return true     }          @objc func tableView(_ tableView: NSTableView, draggingSession session: NSDraggingSession, willBeginAt screenPoint: NSPoint, forRowIndexes rowIndexes: IndexSet) {         // NEVER CALLED     }      }
Posted
by
Post not yet marked as solved
2 Replies
1.3k Views
I have created my first app with python using py2app and it build my app successfully but when I try to open it, it crash but when I open it's package and run it from this path: myapp.app/contents/macos/myapp it open console and run my app correctly without any error. I can't understand how to read this kind of mac errors. I will be happy if you can help me with that: Error Text
Posted
by
Post not yet marked as solved
3 Replies
5.1k Views
I've discovered that my app has a memory leak, where when I close a window, it disappears from the screen but it (along with all its views, view controllers, and associated objects) actually doesn't get released. Instruments doesn't register it as a leak. It does show a few unidentified malloc leaks, but nowhere near enough to account for a window full of stuff. Xcode's memory graph doesn't show any leaks either, and I've combed through it looking for retain cycles or unwanted captures in blocks. I've fixed a few, but it hasn't been enough to actually get the window released. What other tactics are there for finding this kind of leak? The project is here for anyone feeling adventurous: https://github.com/Uncommon/Xit
Posted
by
Post not yet marked as solved
4 Replies
1.2k Views
I've seen this issue all across the internet. I cannot click on the elements of a dropdown/combobox nor the elements of a context menu on the application I have in production for my clients. See this thread on Reddit where people complain of the same exact behaviour on other apps like Microsoft Excel or Spark: https://www.reddit.com/r/MacOSBeta/comments/xb3u0w/office_submenus_not_clickable_in_ventura_thoughts/ I've also seen on my modal windows that the events it receives apply to the parent window. For example a mouse over event will be triggered when my mouse is over the parent window when it should only be triggered when the mouse is over the modal window. Is there a thing Apple will fix before the official macOS Ventura release date or there is something developers should know to fix it by ourselves? This is kinda serious. Please help. Thanks a lot.
Posted
by
Post not yet marked as solved
1 Replies
1k Views
Hello! Since the Stage Manager now occupies a set of interactions left of the screen to display a new dock, we'd like to conditionally turn off features or provide a feature workaround to not conflict with this set of interactions. Is there any way to check in AppKit, whether Stage Manager is currently turned on in the system to accomplish this? Any help would be greatly appreciated!
Posted
by
Post not yet marked as solved
7 Replies
1.3k Views
NSOpenPanel.runModal is returning before the user can select a file. It seemed to get progressively worse as the OS updated. Now with macOS Ventura 13.0 it is completely unusable. Supporting docs https://stackoverflow.com/questions/70050559/nsopenpanel-nssavepanel-runmodal-dismisses-immediately-with-cancel-but-only-on https://stackoverflow.com/questions/28478020/presenting-nsopenpanel-as-sheet-synchronously
Posted
by
Post not yet marked as solved
4 Replies
1.6k Views
Is there a way to force a window to resize according to an aspect ratio? This is possible in AppKit via the NSWindow.contentAspectRatio property but I cannot find something similar for SwiftUI. Basically, I want the window to maintain the aspect ratio of its contents.
Posted
by
Post not yet marked as solved
3 Replies
2.9k Views
I'm getting these log messages: +[CATransaction synchronize] called within transaction whenever I spawn or resize and NSOpenPanel (or save panel). To investigate, I created the simplest possible test app, with no window and only this method that I override in AppDelegate.m: - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { NSOpenPanel *panel = NSOpenPanel.openPanel; panel.allowedFileTypes = @[@"public.plain-text"]; [panel beginWithCompletionHandler:^(NSModalResponse result) { }]; } This is basically all the code I added. And this still triggers the warning message above. The message is also posted whenever I resize the panel. I wasn't getting these messages before updating to Ventura. What am I doing wrong?
Posted
by