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

AppKit Documentation

Posts under AppKit tag

244 Posts
Sort by:
Post not yet marked as solved
1 Replies
465 Views
All:Similar to this post, I've created a view controller scene in a macOS app to which I've added a stock NSTableView. I've changed nothing, meaning it has regular highlighting, allows column selection. Even though I can click to select a column and get that selected column index in code, the selection is never highlighted.I'm using Xcode 8.2.1 with a newly-created document-based macOS application project. I do nothing to the table view (aside from asking it to reloadData() ) in code. The standard project's setup means the root view of this view controller (the window's content view controller) is layer-backed. I've tried deleting and re-adding the table view, tried toggling highlighting and column selectability (including toggling "allows multiple") in code and in IB, but nothing seems to be working. I find this ... extremely odd after years of Cocoa development (admittedly, on apps that support much older verisons of OS X).Any suggestions?
Posted
by
Post not yet marked as solved
6 Replies
2.2k Views
I'm writing an app in swift that is being localized and I have a question around formatting integers.Here is a simplified version of my Localizable.stringsdict file:<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>RecordsFound</key> <dict> <key>NSStringLocalizedFormatKey</key> <string>%#@value@</string> <key>value</key> <dict> <key>NSStringFormatSpecTypeKey</key> <string>NSStringPluralRuleType</string> <key>NSStringFormatValueTypeKey</key> <string>d</string> <key>one</key> <string>$d record found</string> <key>other</key> <string>$d records found</string> </dict> </dict> </plist>Making this call:String(format: NSLocalizedString("RecordsFound", comment: ""), 1)returns "1 record found" (singular) and making this call:String(format: NSLocalizedString("RecordsFound", comment: ""), 2)returns "2 records found" (plural).All good so far. However making this call:String(format: NSLocalizedString("RecordsFound", comment: ""), 15387)returns "15387 records found". I'd like it to return "15,387 records found" (with the thousand separator). My Language & Region settings are set to use thousand separators but it doesn't seem to pick this up.I could use NumberFormatter but of course that returns a string which breaks the pluralization rules. I could also pass 2 parameters (the integer itself and a string representation of the integer) but that gets messy especially when there are already multiple integers being passed (some of my strings contain multiple integers and therefore multiple pluralization rules - one for each integer).Is it possible to add formatting rules to integers in Localizable.stringsdict? If not what's the recommended method of doing this?
Posted
by
Post marked as solved
13 Replies
9.3k Views
I would like to create a macOS app without using Interface Builder.How must the Xcode macOS app template be modified after deleting Main.storyboard and its corresponding Info.plist lineto show a single simple window at startup?
Posted
by
Post not yet marked as solved
3 Replies
742 Views
Hi there,we are getting frequent questions from our user base when they cannot find options in the print dialog of our app because the details in NSPrintPanel are not expanded by default.Is there a way to always expand the details section programmatically to make it easier for our non-technical user base to find the app specific print settings..?Browsing the NSPrintPanel documentation didn't reveal anything obvious..Cheers,Jay
Posted
by
Post not yet marked as solved
1 Replies
413 Views
I'm experimenting with the Accessibility API and I'm currently trying to interrogate the system wide accessibility element.According to AXUIElementCopyAttributeNames the system wide element has 4 attributes (AXRole, AXRoleDescription, AXFocusedUIElement & AXFocusedApplication).I can successfully use the following chunk of code to get the attribute value for the AXRole and AXRoleDescription elements but when I try to get the value of the AXFocusedUIElement or AXFocusedApplication attributes AXUIElementCopyAttributeValue returns kAXErrorCannotComplete.AXUIElementRef systemWideElement = AXUIElementCreateSystemWide(); CFStringRef attrName = kAXFocusedApplicationAttribute; CFTypeRef value = NULL; res = AXUIElementCopyAttributeValue(systemWideElement, attrName, &value); if (res != kAXErrorSuccess) NSLog(@"Failed to get element attribute %@ (%d)", attrName, (int)res); if (value) CFRelease(value);Does anybody know why AXUIElementCopyAttributeValue is returning kAXErrorCannotComplete / what I'm doing wrong?Thanks
Posted
by
Post not yet marked as solved
3 Replies
4.8k Views
Hey guys,My iOS application has an extension that detects device Unlock and Lock event. I found 2 separate API to detect. Both of them work great.But my code is rejected twice by Apple Review Team. The following reason was to reject our binary.From AppleGuideline 2.5.1 - Performance - Software RequirementsYour app uses or references the following non-public APIs:com.apple.springboard.lockcompletecom.apple.springboard.lockstate1. First solution to detect device lock and unlock-----------------------------------Code Starts here-----------------------------------#import <notify.h> int notify_token; notify_register_dispatch("com.apple.springboard.lockstate", ¬ify_token, dispatch_get_main_queue(), ^(int token) { uint64_t state = UINT64_MAX; notify_get_state(token, &state); if(state == 0) { self->lastActiveDate = [NSDate date]; self->deviceCurrentState = _DEVICE_LOCK_STATE_UNLOCKED; } else { self->deviceCurrentState = _DEVICE_LOCK_STATE_LOCKED; } } );-----------------------------------End of Code-----------------------------------2. Second solution to detect device lock and unlock-----------------------------------Code Starts here------------------------------------(void)registerforDeviceLockNotif { //Screen lock notifications CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), //center CFBridgingRetain(self), // observer displayStatusChanged, // callback CFSTR("com.apple.springboard.lockcomplete"), // event name NULL, // object CFNotificationSuspensionBehaviorDeliverImmediately); CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), //center CFBridgingRetain(self), // observer displayStatusChanged, // callback CFSTR("com.apple.springboard.lockstate"), // event name NULL, // object CFNotificationSuspensionBehaviorDeliverImmediately); } - (void)removeDeviceLockNotif { CFNotificationCenterRemoveObserver(CFNotificationCenterGetDarwinNotifyCenter(), CFBridgingRetain(self), CFSTR("com.apple.springboard.lockstate"), nil); CFNotificationCenterRemoveObserver(CFNotificationCenterGetDarwinNotifyCenter(), CFBridgingRetain(self), CFSTR("com.apple.springboard.lockcomplete"), nil); }-----------------------------------End of Code-----------------------------------Since we are unable above 2 part of codes, what solution or what API we would use to detect device lock and unlock events? Thank you.
Posted
by
Post not yet marked as solved
5 Replies
19k 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
16 Replies
4.3k Views
Hi everyone,Anyone else seeing crashes like this:Fatal Exception: NSInvalidArgumentException. -[_UISnapshotWindow actualSceneBounds]: unrecognized selector sent to instanceSeems to be happening in low memory situations.Any easy fix? Our app isn't using a huge amount of RAM.Thanks
Posted
by
Post not yet marked as solved
1 Replies
332 Views
The PDFDocument class makes updating metadata attributes simple but appears to:Disallow arbitrary values for the /Producer attribute - the wite action substitutes an Apple string as the producerOffer no choice over the PDF version or the write format - it's 1.4, and compressed regardless of the original PDF formatAm I missing something simple in the PDFDocument class that will over-ride this behaviour?Is the PDFDocument structure archive conformant and, if so, to what level?Is it necessary to deal directly with CGPDFDocument to overcome these limitations?cheers,david
Posted
by
Post not yet marked as solved
1 Replies
681 Views
I need to implement minimal Cocoa application without Xcode. I am trying this example:https://www.cocoawithlove.com/2010/09/minimalist-cocoa-programming.html#import <Cocoa/Cocoa.h>int main(){ [NSAutoreleasePool new]; [NSApplication sharedApplication]; [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; id menubar = [[NSMenu new] autorelease]; id appMenuItem = [[NSMenuItem new] autorelease]; [menubar addItem:appMenuItem]; [NSApp setMainMenu:menubar]; id appMenu = [[NSMenu new] autorelease]; id appName = [[NSProcessInfo processInfo] processName]; id quitTitle = [@"Quit " stringByAppendingString:appName]; id quitMenuItem = [[[NSMenuItem alloc] initWithTitle:quitTitle action:@selector(terminate:) keyEquivalent:@"q"] autorelease]; [appMenu addItem:quitMenuItem]; [appMenuItem setSubmenu:appMenu]; id window = [[[NSWindow alloc] initWithContentRect:NSMakeRect(10, 10, 200, 200) styleMask:NSTitledWindowMask backing:NSBackingStoreBuffered defer:NO] autorelease]; [window setTitle:appName]; [window makeKeyAndOrderFront:nil]; [NSApp activateIgnoringOtherApps:YES]; [NSApp run]; return 0;}It works well, except for one little problem: Immediately after the launch, menu is altered, but is inactive (clicking it does nothing). If I select some other application and then get back to that minimal one, menu starts working as expected.Any idea how to fix this?
Posted
by
Post not yet marked as solved
7 Replies
1.7k Views
I am trying to understand how an NSTextField reacts to changes of its cell's backgroundStyle.The reason is that I want to use the automatic handling of the text color be used when I set the backgroundStyle of the text field that's inside a table cell.From what I have gathered so far, the textfield's cell has a backgroundStyle property and when this is set, and the textColor is `labelColor` (or any of the other control colors) the text color should be automatically updated to be fitting for the backgroundStyle.Given a tableView with a custom row class and a custom cell:class RowView: NSTableRowView { override func drawSelection(in dirtyRect: NSRect) { if isSelected { NSColor.white.set() var rects: UnsafePointer<NSRect>? = nil var count: Int = 0 self.getRectsBeingDrawn(&rects, count: &count) for i in 0..<count { let rect = NSIntersectionRect(bounds, rects![i]) __NSRectFillUsingOperation(rect, NSCompositingOperation.sourceOver) } } } override var interiorBackgroundStyle: NSView.BackgroundStyle { return isSelected ? .light : .dark } }andclass CustomCellView: NSTableCellView { @IBOutlet weak var label: NSTextField! override var backgroundStyle: NSView.BackgroundStyle { didSet { Swift.print("Style set to \(backgroundStyle == .light ? "light" : "dark")") Swift.print("Label Style set to \(label.cell!.backgroundStyle == .light ? "light" : "dark")") } } }I would expect the label to be drawn in black, when I select the row.I can see that the backgroundStyle is forwarded correctly when I select the row, but the label doesn't change color at all. In fact, being seemingly blended with my white selection, the label disappears entirely.Why is the label color not changing?P.S.: I know that I can manually set the label's color based on the background style of the cell. That's not what I am asking. I want to use the convenience of the `controlTextColor`s or at least understand why they are not working in this case. (They do seem to work if I don't draw my custom selection in the row and use the standard blue selection)
Posted
by
Post not yet marked as solved
5 Replies
9.3k Views
I have tried my app on severals devices but some of theme show this error in Xcode console:objc[8430]: Class DeviceType is implemented in both /System/Library/PrivateFrameworks/DeviceIdentity.framework/DeviceIdentity (0x1b36a3908) and /private/var/containers/Bundle/Application/669AA1E2-7EC3-45B7-B4A2-BA187FC99643/app3.app/Frameworks/PVModel.framework/PVModel (0x101cfe6a0). One of the two will be used. Which one is undefined.I believe that the `/System..` directory dose not have anything to do with my app and Xcode should not be looking class there.I tried to set the search path in Xcode build settings, but the error still shows upHow can I answer to this "Which one is undefined." ? How can specify which one to be used ?Or how can I prohibite Xcode from searching into directories outside the app bundle?
Posted
by
Post not yet marked as solved
5 Replies
764 Views
Hello,I'd like to add a dropdown to a NSSearchField with different filters, like the search field in iTunes.I'm new to Cocoa but I was a Flash / Flex develop which has many similarities with the subclassing and I'm looking for the methods to subclass, or is it better to compose with the NSSearchField in a XIB ?I tried to subclass the draw method with a super call but as soon as I do that, the NSSearchField lose its focus animation.Thx a lot.
Posted
by
Post not yet marked as solved
5 Replies
4k Views
Hello,I am maintaining a legacy application and we have an issue when migrating from 10.13 SDK to 10.14 SDK.The failing code is trying to open a NSWindow modally. This NSWindow contains a NSOpenGLView. Hidden part of the call stack is just internal C++ code, nothing related to Cocoa. As you can see at the top of the stack, a NSException gets thrown and contains this message: "The window has been marked as needing another Display Window pass, but it has already had more Display Window passes than there are views in the window."Callstack: https://cl.ly/8399f31a5ee8Only changing back to 10.13 SDK makes this issue go away. After reading 10.14 SDK release notes, I've the impression that this comes from the changes in Cocoa layer backing. This is described starting from slide 109 of https://developer.apple.com/videos/play/wwdc2018/209/Unfortunately, slide 123 says that:Implementation details for NSOpenGL are differentOpenGL is deprecatedUse MTKViewSo I don't have any clue about what is the recommended behavior in my case. I'm not in a drawRect call and I disabled all the parts of the code that I think could trigger -[NSView/NSWindow display] calls but I still get the exception, so I don't really know what to do. Right now removing the NSOpenGLView is not an option, and doing so doesn't guarantee that the exception would go away.In the time being I use 10.13 SDK with Xcode 10 but if you know how it could be fixed and to allow me to use 10.14 SDK, I'm interested!Best regards,Lucas
Posted
by
Post marked as solved
6 Replies
5.2k Views
Folks;When I run an archived copy of my mac application on a test dev machine (not my main dev box) I see errors in the Console log that trouble me...1) I see this error immediately before any of my code executes!error 16:14:25.839821 -0700 [MYAPPNAME] Couldn't read values in CFPrefsPlistSource<0x6000000ed280> (Domain: [MYAPPBUNDLEID], User: kCFPreferencesCurrentUser, ByHost: No, Container: (null), Contents Need Refresh: Yes): accessing preferences outside an application's container requires user-preference-read or file-read-data sandbox access, detaching from cfprefsdI open my standard defaults (a .plist) in -awakeFromNib like so: NSUserDefaults *ud = [NSUserDefaults standardUserDefaults]; [ud registerDefaults:[NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"WhodoMacOSDefaults" ofType:@"plist"]]]; [ud setObject:launch_Date forKey:kKudosLaunchDate];This activity throws 2 of these errors in the console:error 16:14:26.429881 -0700 [MYAPPNAME] attempt to set <private> for key in <private> in non-persistent preferences domain CFPrefsPlistSource<0x6000000ed280> (Domain: [MYAPPBUNDLEID], User: kCFPreferencesCurrentUser, ByHost: No, Container: (null), Contents Need Refresh: Yes)Then subsequently every 'set' for NSUserDefaults throw another of these into the console log...Nothing fancy going on in this app: no app groups, no iCloud, no hardened runtime...I don't see a 'user-preference-read' option in the standard entitlement document. Am I missing some basic conguration setting?Is this all just a by-product of running a 'development' archive?Any thoughts appreciated!Steve
Posted
by
Post marked as solved
12 Replies
1.1k Views
I'm trying to write a game for MacOS and I'd like to be able to provide a menu option, when the app isn't running, that allows them to jump straight back to the last game level they were playing. My limited understanding is that NSDockTilePlugins is the correct way to do this, as from MacOS 10.6, but I cannot find an actual Objective C tutorial from Apple on how to implement this correctly?Is this the only way to implement non-runtime menus? Can anyone please point me in the right direction?
Posted
by
Post not yet marked as solved
3 Replies
3.5k Views
In my MacApp I am using custom fonts. These fonts are stored in /Resourcese/Fonts folder and Copy phase is written for the same.I noticed that, if I have used these fonts in Xib and I run the app from Xcode. UI does not show up these fonts unless it is installed in Font Book.However, same build if I have published to AppStore and I download from AppStore, custom fonts does show up.My question is that why does Custom font not show up while we run through Xcode?-Srinivas
Posted
by
Post not yet marked as solved
2 Replies
856 Views
Hello,I am facing the following issue:I have a custom framework (iOS) which has dependancy of another 3 frameworks. The framework is written in Objective C. While developing with no problems at all, I recently recieved build errors:Declaration of 'jmp_buf' must be imported from module 'Darwin.C.setjmp' before it is required Could not build module CoreFoundation Could not build module Foundation Could not build module UIKit Could not build module CoreGraphicsI haven't change any system files or files from some system framework. Interesting is that If I install the framework on separate mac with the same xcode I get build success. After a while I get these errors again. 😐Screenshot-2020-05-12-at-10-29-42 — ImgBB I am also attaching a screenshot.I already tried cleaning derived data, clean build, clean build folder.. I even re-install Xcode and still the sameSometimes on real device is bulding with success on simulator not, but most of the time on both places is with this error.Xcode version: 11.4.1macOS Catalina version: 10.15.4Real device tested: iPhone XS 13.4.1Simulator tested: iPhone 11 13.4.1 and iPhone X 12.4
Posted
by
Post marked as solved
6 Replies
3.0k Views
macOS, SwiftIs it possible to remove the scroll in WebKit View? (or make it not visible)I have a WebKit View from library and I have made the connection to the ViewController.swift:@IBOutlet weak var webView1: WKWebView!
Posted
by