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

AppKit Documentation

Posts under AppKit tag

245 Posts
Sort by:
Post not yet marked as solved
1 Replies
160 Views
I created a custom keyboard layout with the app Ukelele, based on a built-in layout and thus using the original icon. However, the icon is not loaded as a template image in the Menu Bar. The result is that when a darker background image is used (or a dynamic background turns darker), the black part of the icon does not switch to white and all I see is a black square with the letters of the keyboard layout not readable: This was fine until 12.3 when flags were used as icons instead. Is this a bug and is there a way to workaround this?
Posted
by Niko18.
Last updated
.
Post not yet marked as solved
0 Replies
83 Views
I recently updated my sandboxed application to the MacOS 12 target. Among deprecation, there is the allowedFileTypes method for NSOpenPanel/NSSavePanel, replaced with allowedContentTypes. I updated my document opening and importing methods to reflect this change. For example, to import a CSV or JSON file, I coded: myPanel.allowedContentTypes = [NSArray arrayWithObjects:UTTypeJSON, UTTypeCommaSeparatedText, UTTypeTabSeparatedText, [UTType typeWithIdentifier: @"org.openxmlformats.spreadsheetml.sheet"], nil] ; All these UTTypes are described in the "Imported Type UTIs" section of the app's Info.plist. Unfortunately, it is impossible to select any of Json, Csv or Xlsx file in the NSOpenPanel since I made these changes to be in line with MacOS12 requirements. Worse, I cannot open my own file format with its own UTI (described in Info.plist too)! The only way to open/import is to set myPanel.allowOtherFileTypes to TRUE, and to remove any code referring to allowedContentTypes. What is quite strange is that exporting works correctly after updating. My spotlight plugin works also (for my file format)… Something I missed? Help welcome as my app became useless since I made these changes, and I use it every day for my work (and improving it before launching it on the Appstore)
Posted Last updated
.
Post not yet marked as solved
4 Replies
1.2k Views
I am integrating FinderSync Extension in my Cocoa Application to show badges in files and folders. Look at the below two scenario:1) When i run application using FinderSync Extension (like DemoFinderSync), in that case Extension is added in the System Preference with Check mark and called that principal class "FinderSync.m" as well.2) When i run application using my Application Scheme (like DemoApp) , in that case Extension is added in the System Preference but without check mark and that principal class "FinderSync.m" do not call and FinderSync Extension does not work in this case.So anybody have an idea how to enable Finder Extension in the System Preference using second scenario.Also post your answer in the below StackOverflow link:http://stackoverflow.com/questions/31176942/how-to-enable-findersync-extension-in-the-system-preference-in-cocoa-objectiveAny help is appreciated..!!
Posted
by Max360.
Last updated
.
Post not yet marked as solved
0 Replies
120 Views
Looking for a Cocoa example/tutorial in Objective C, on how to create a 400x90 pixel panel with outlets for a progress bar, textfield and a button (stop) to display temporarily while images are loading. I've added a WindowController + xib to the app's main storyboard but don't know how to use it to access the outlets in the progress panel.
Posted
by DrMiller.
Last updated
.
Post marked as solved
1 Replies
155 Views
Hi everyone, It is the first time for me working with AppKit and a NSTableView. It is backed by a NSFetchedResultsController for Core Data. When there are changes to the dataset, a Notification is being sent: func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { guard let links = self.fetchedResultsController.fetchedObjects else { return } if self.viewContext.hasChanges { try? self.viewContext.save() } self._links = links NotificationCenter.default.post(name: .reloadLinkList, object: nil) } NotificationCenter.default.publisher(for: .reloadLinkList).receive(on: RunLoop.main).sink { notification in self.list.tableView.reloadData() self.list.linksModel.selectedRows = IndexSet([]) } .store(in: &cancellables) This works great for inserting and updating data. When I try to delete something, I get: Thread 1: Fatal error: UnsafeRawBufferPointer with negative count The code for deleting selected objects looks as following: // selector methode for UIMenuItem`s action @objc func onDeleteSelectedLinks(_ sender: AnyObject) { list.linksModel.deleteLinks(links: selectedLinks) } // Method for deleting links from the view context func deleteLinks(links: [LBLink]) { for link in links { self.viewContext.delete(link) } } Thank you for any help in advance!
Posted
by dhaydl.
Last updated
.
Post not yet marked as solved
0 Replies
72 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 Last updated
.
Post not yet marked as solved
0 Replies
95 Views
I have an Objective-C macOS app which provides a service that provides unique services on selected text. This app has been for sale in the Mac App Store for several years. The app registers as service provider during 'appDidFinishLaunching' with: [[NSApplication sharedApplication] setServicesProvider:self]; When my service is invoked it uses the standard service method: (void)serviceName:(NSPasteboard *)pboard userData:(NSString *)userData error:(NSString **)error In the body of this standard service method the contents of the NSPasteboard (pboard) are examined and consumed by my app. - (void) kudosService:(NSPasteboard *)pboard userData:(NSString *)userData error:(NSString **)error; { if ([pboard pasteboardItems].count==0) { return; } NSPasteboardItem *pI = [pboard pasteboardItems][0]; NSLog(@"pI:%@",pI.types ); for (NSString *uti in pI.types) { NSLog(@"uti:%@ string:%@",uti, [pI stringForType:uti] ); } ... } Something has changed with Preview app; at this point I'm inclined to think the change occurred with version 11. Console output for Preview pI:( "public.utf8-plain-text", "public.rtf", "public.utf16-external-plain-text" ) uti:public.utf8-plain-text string:(null) uti:public.rtf string:(null) uti:public.utf16-external-plain-text string:(null) This is the output regardless of whether or not the user has a mere text selection OR has formally 'Cop(ied)' [Cmd-C] the text in the Preview window! Please NOTE if I open the exact same .pdf document in Safari and invoke the service from Safari I see the expected Console output: pI:( "public.utf8-plain-text" ) uti:public.utf8-plain-text string:The Best Gluten-Free Chocolate Cake When did this change in Preview behavior occur? Can anyone point me to some documentation, which I have obviously overlooked, that would shed some light on this matter!
Posted
by SwampDog.
Last updated
.
Post not yet marked as solved
10 Replies
775 Views
I have a persistent "crash" with at least one of my apps, which appears to be a case of the app either quitting or being force-quit without generating a crash log. The app doesn't subscribe to any sudden termination compatibility or similar. I have a good friend who is a developer who is able to reproduce the issue within minutes, so I've captured a trove of information from him including a complete sysdiagnose. Unfortunately nothing is jumping out at me, and the only things that show up that seem like they might be related are keys like ApplicationWouldBeTerminatedByTAL and NSCanQuitQuietlyAndSafelyKey. I am kind of grasping at straws and would welcome any inspiration anybody can share. What is TAL and is it something the system could be imposing on my app? If there are circumstances where macOS will preemptively terminate a running app, what are they, and how can I figure out which one is causing the quits in these situatoins? I'd love to be able to reproduce the behavior on my own Mac. If it's something I can prevent, great, if it's not, it would be good to know how to distinguish it from a regular crash for reporting purposes. Thanks for any help!
Posted
by jalkut.
Last updated
.
Post marked as solved
2 Replies
217 Views
This question is mainly just a point of curiosity and education. I'm working on one of my first macOS apps, and I see I can check NSApplication.shared.windows to get a list of all the application's windows. Most of the time, this list contains the windows I've programmed which are in memory. Sometimes, though, it also contains two instances of NSMenuWindowManagerWindow. This doesn't appear to be a documented type, and I'm inferring I'm seeing evidence of something NSApplication or the system is doing to help deliver or render some kind of standard application behaviour. I'm wondering whether any macOS gurus (or engineers) can shine some light on it.
Posted
by Starfia.
Last updated
.
Post not yet marked as solved
2 Replies
199 Views
In trying to implement a custom variation of HSplitView/VSplitView for macOS, I found it impossible to achieve correct behavior of the NSCursor while dragging the split view divider. Something else is resetting NSCursor to an arrow cursor when a SwiftUI view updates. Moving the mouse over the divider View changes the NSCursor to a resize cursor. However, when the insertion is blinking, after 1/2 a second, on the blink the cursor changes back to an arrow. Turning off "blink", then hovering over the divider, the NSCursor stays as a resize cursor. However, as soon as you click and drag to move the divider, again it changes back to an arrow cursor, flashing between the two NSCursor as you move the divider. It seems like something in SwiftUI is doing this, but I can't tell. Is it possible to implement a custom VSplitView within SwiftUI and achieve consistent behavior of the NSCursor? Full code below import AppKit import SwiftUI @main struct NSCursorBugApp: App { var body: some Scene { WindowGroup { ContentView() } } } let blinkTimer = Timer.publish(every: 0.5, on: .main, in: .common).autoconnect() struct ContentView: View { @State var position = 20.0 @State var opacity = 1.0 @State var blink = true var body: some View { VStack(alignment: .leading, spacing: 0) { Color.gray .frame(height: position - 4) .overlay{ Rectangle().frame(width: 1, height: 20).opacity(opacity).padding(.trailing, 200).padding(20) } PaneDivider(position: $position) Color.cyan Toggle("Blink", isOn: $blink) } .onReceive(blinkTimer) {_ in if blink { opacity = 1 - opacity } } .frame(width: 500, height: 500) .coordinateSpace(name: "stack") } } struct PaneDivider: View { @Binding var position: Double let dividerSize = 8.0 let circleSize = 6.0 var body: some View { Group { Divider() ZStack { Rectangle().fill(Color(white: 0.99)) Circle().frame(width: circleSize, height: circleSize).foregroundColor(Color(white: 0.89)) }.frame(height: 8) Divider() } #if os(macOS) .background(NSCursorView()) #endif .gesture(DragGesture(minimumDistance: 1, coordinateSpace: .named("stack")) .onChanged { position = max(0, $0.location.y) }) } } /// Helper NSView as .background to SwiftUI PaneDivider View to set resize NSCursor when inside view bounds class NSCursorPlatformView : NSView { var horizontal = true var trackingArea: NSTrackingArea? = nil func clearTrackingAreas() { if let trackingArea = trackingArea { removeTrackingArea(trackingArea) } trackingArea = nil } override func updateTrackingAreas() { clearTrackingAreas() let area = NSTrackingArea(rect: bounds, options: [.mouseEnteredAndExited, .mouseMoved, .activeInKeyWindow], owner: self, userInfo: nil) addTrackingArea(area) trackingArea = area } override func viewWillMove(toWindow newWindow: NSWindow?) { if newWindow == nil { clearTrackingAreas() } else { updateTrackingAreas() } } override func mouseEntered(with event: NSEvent) { updateCursor(with: event) } override func mouseExited(with event: NSEvent) { updateCursor(with: event) } override func mouseMoved(with event: NSEvent) { updateCursor(with: event) } override func cursorUpdate(with event: NSEvent) {} // to stop system from resetting cursor after us func updateCursor(with event: NSEvent) { let p = convert(event.locationInWindow, from: nil) if bounds.contains(p) { (horizontal ? NSCursor.resizeUpDown : NSCursor.resizeLeftRight).set() } else { NSCursor.arrow.set() } } } struct NSCursorView: NSViewRepresentable { var horizontal = true func makeNSView(context: Context) -> NSCursorPlatformView { let view = NSCursorPlatformView() view.horizontal = horizontal return view } func updateNSView(_ nsView: NSCursorPlatformView, context: Context) { } }
Posted
by avitzur.
Last updated
.
Post not yet marked as solved
0 Replies
98 Views
Is there a simple way to create an NSFontCollection based on NSFontDescriptor querying to gather all installed/available fonts with a MATH table? It doesn't look like there's an attribute for that, but I don't know how else to search other than correlating with features like ssty, dtls, and flac.
Posted
by TyngJJ.
Last updated
.
Post not yet marked as solved
0 Replies
110 Views
I would like to be able to get either the key code or the characters/text from an NSEvent/KeyEvent. Absolutely no idea how to do this as the documentation I have found so far has been very limited. I believe I need to create an instance of NSEvent but I do not know how. My script is below. I am working on a speedrun macro for Minecraft. This script is fully functioning as is, but currently all it does is check if the control key has been pressed via checking the modifier flags of NSEvent. use framework "AppKit" use scripting additions global ca set ca to current application # you may change the following variables global seed set seed to "8398967436125155523" # do not change anything below this line to isModifierPressed(modifier) ((ca's NSEvent's modifierFlags()) / modifier as integer) mod 2 is equal to 1 end isModifierPressed repeat if isModifierPressed(ca's NSEventModifierFlagControl) then execute() delay 0.01 end repeat on execute() tell application "System Events" delay 0.1 keystroke tab delay 0.02 keystroke return delay 0.02 repeat 3 times keystroke tab delay 0.02 end repeat keystroke return delay 0.02 repeat 2 times keystroke tab delay 0.02 end repeat repeat 3 times keystroke return delay 0.02 end repeat repeat 4 times keystroke tab delay 0.02 end repeat keystroke return delay 0.02 repeat 3 times keystroke tab delay 0.02 end repeat keystroke seed delay 0.02 repeat 6 times keystroke tab delay 0.02 end repeat keystroke return end tell end execute
Posted Last updated
.
Post marked as solved
2 Replies
158 Views
We want to have a login window stay in front and key, until the user signs in. We want it to stay in front even if switching away from it. Now, this does seem possible, since zoom just did it to me while I was getting into a call to discuss this, but I can't figure out how. In this particular case, I am instantiating an NSViewController subclass, and then creating an NSWindow for it to use. I have tried setting the NSWindow.level to all sorts of values, and they don't seem to work. help?
Posted
by kithrup.
Last updated
.
Post not yet marked as solved
7 Replies
425 Views
Buenas tardes, I have a problem with a control inside an nsalert from a thread calling it on the main thread. Everything works fine but the textfield does not respond, you write or delete and it has no response. dispatch_sync(dispatch_get_main_queue(), ^{ NSAlert *alert = [[NSAlert alloc] init]; [alert setMessageText:@"Enter PIN"]; [alert addButtonWithTitle:@"OK"]; [alert addButtonWithTitle:@"Cancel"]; NSSecureTextField *input = [[NSSecureTextField alloc] initWithFrame:NSMakeRect(0, 0, 200, 24)]; [input setStringValue:@""]; [alertsetAccessoryView:input]; [inputsetEditable:true]; NSInteger button = [alert runModal]; if (button == NSAlertFirstButtonReturn) { self.pin = [input stringValue]; [self.wait signal]; }else if (button == NSAlertSecondButtonReturn) { [Utils Log:@"Pin canceled!"]; [alert.window close]; [self.wait signal]; } }); If I try to create an NSWindow, it comes out as disabled and the controls can't be used either. Thanks greetings
Posted
by Aekold.
Last updated
.
Post not yet marked as solved
0 Replies
135 Views
Hi, I am using AVRoutePickerView on macOS via NSViewRepresentable. I am setting the player property with a AVPlayer object. But when I choose via AVRoutePicker one of my HomePods, AVPlayer is ignoring the setting and is still using my Mac as output. Strangely if I left the player property nil and then choosing one of my HomePods via AVRoutePickerView it is working, but only for one AVPlayer, other AVPlayer will be muted. How can I force AVRoutePickerView to use its AVPlayer property? I am testing this with macOS 12.4. Thank you Oleg
Posted
by omg.
Last updated
.
Post not yet marked as solved
0 Replies
119 Views
I have an older MacOS app where in IB (no storyboards) I created a main window/view and a progress window/view in one xib in response to a menu item. In a new MacOS app (using much of the code from the older menu item code), in IB storyboard I have a window controller/window/view/subviews in the storyboard, but I cannot seem to find a way to also include in the storyboard a progress panel (to hook up to an outlet in the view controller). I can create the same window/panel/progress bar that I had in the older app in a separate xib. So I suppose (in objective c) I can just load the xib??? So, is there a better way to implement a separate progress window(s) in a storyboard and hook them up to outlets? I think I'm missing something And what happened to NSPanels?
Posted
by DrMiller.
Last updated
.
Post not yet marked as solved
3 Replies
303 Views
A type of question I see often is "which UI framework is best? SwitUI, UIKit, AppKit, etc?" And the answer is, of course, usually "it depends" or "a mix, depending on what you need". I wanted to re-frame that question with specific parameters. Let's say you were writing Apple Photos for the Mac from the ground up, starting today. For the sake of discussion, it's going to be functionally identical to the Photos app that exists on the Mac today. Which means it: looks and feels like a true, native macOS app should be very performant in terms of rendering and scrolling through a library that may contain hundreds of thousands of photos maintains a large database which can be synced over iCloud etc When you go to write that first line of UI code, which UI framework are you reaching for, and why? If more than one, which ones would you use for each piece, and why? Especially interested to hear any viewpoints from Apple folks in this thought exercise!
Posted
by stevenf.
Last updated
.
Post marked as solved
4 Replies
364 Views
I have an executable (Google Chrome) that apparently "is running setugid()". I cannot find a way to make it work when called from within a /usr/bin/sandbox-exec sandbox without sudo. Given the following sandbox profile: (version 1) (allow process-exec (literal "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome") (literal "/usr/bin/sudo") (with no-sandbox) ) The following two commands work: /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome /usr/bin/sandbox-exec -f ./profile.sb sudo /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome (although the second one is really not smart) but this does not work: $ /usr/bin/sandbox-exec -f ./profile.sb /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome 2022-06-07 23:06:50.267 Google Chrome[21533:679255] The application with bundle ID com.google.Chrome is running setugid(), which is not allowed. Exiting. I'm not sure what's preventing chrome from "running setugid()". I've read somewhere that it's something called "AppKit", but I'm not sure how it gets involved here. Is there a way to have sandbox-exec allow the chrome process to do what it needs, without sudo? Any help is appreciated.
Posted
by nmattia.
Last updated
.
Post not yet marked as solved
2 Replies
236 Views
I'm working on an iPad app, which I want to be able to run properly on the M1 Mac. I am not using Mac Catalyst because I am using OpenGL, which is not available for Catalyst. Instead, I am targeting "My Mac(Designed for iPad) when I build for the M1 Mac. I would like to know when my app has been placed in full screen mode (when running on the M1 Mac). MacOS (AppKit?) provides the "NSWindowDidEnterFullScreenNotification" to help with this. In general, I'd love to be able to access these "NSWindow*" notifications from within my iOS app, but specifically, I get the error: "Use of undeclared identifier 'NSWindowDidEnterFullScreenNotification' when I use "[NSNotificationCenter defaultCenter] addObserver" to get notified when my app goes full screen. Any ideas as to how I can bridge this gap between iOS and MacOS and get notifications from MacOS, without resorting to Mac Catalyst? This capability would be extremely useful.
Posted
by JohnLocke.
Last updated
.
Post marked as solved
2 Replies
179 Views
I was experimenting with NSSpellChecker on a macOS app with Swift and I noticed that when there are no spelling mistakes it returns an out of bounds range, specifically one with a lowerBound equals to the max value of a 64-bit signed integer. Am I doing something wrong or is it a bug on Apple's part? let sentence = "What a beautiful world." let range = NSSpellChecker.shared.checkSpelling(of: sentence, startingAt: 0) // "What a beautiful world." range: {9223372036854775807, 0} // "What a beautiful worldk." range: {17, 6}
Posted
by Nasonov.
Last updated
.