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

AppKit Documentation

Post

Replies

Boosts

Views

Activity

How to drag and drop an image file to find in an app
import Cocoa @available(macOS 10.13, *) let imagePboardType = NSPasteboard.PasteboardType.fileURL class DragSourceView: NSImageView { weak var dragSourceDelegate: NSDraggingSource? override func mouseDown(with event: NSEvent) { //拖放数据定义 let pasteboardItem = NSPasteboardItem() //设置数据的Provider if #available(macOS 10.13, *) { pasteboardItem.setDataProvider(self, forTypes: [NSPasteboard.PasteboardType.fileURL]) } else { // Fallback on earlier versions } //拖放item let draggingItem = NSDraggingItem(pasteboardWriter: pasteboardItem) draggingItem.draggingFrame = NSRect(x: 100 , y: 10, width: 100, height: 100) //拖放可视化图象设置 draggingItem.imageComponentsProvider = { let component = NSDraggingImageComponent(key: NSDraggingItem.ImageComponentKey.icon) component.frame = NSRect(x: 0, y: 0, width: 16, height: 16) component.contents = NSImage(size: NSSize(width: 32,height: 32), flipped: false, drawingHandler: { [unowned self] rect in { self.image?.draw(in: rect) return true }() } ) return [component] } //开始启动拖放sesson self.beginDraggingSession(with: [draggingItem], event: event, source: self.dragSourceDelegate!) } } extension DragSourceView: NSPasteboardItemDataProvider { func pasteboard(_ pasteboard: NSPasteboard?, item: NSPasteboardItem, provideDataForType type: NSPasteboard.PasteboardType) { // let data = self.image?.tiffRepresentation let data = "/Users/slowdony/Desktop/640.jpeg" let dataUrl = data.data(using: String.Encoding(rawValue: NSUTF8StringEncoding))! item.setData(dataUrl, forType: type) } } import Cocoa class ViewController: NSViewController { @IBOutlet weak var sourceView: DragSourceView! override func viewDidLoad() { super.viewDidLoad() self.sourceView.dragSourceDelegate = self } } extension ViewController: NSDraggingSource { //返回拖放操作类型 func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor context: NSDraggingContext) -> NSDragOperation { if (context == .outsideApplication){ return .copy } else{ return .generic } } //开始拖放代理回调 func draggingSession(_ session: NSDraggingSession, willBeginAt screenPoint: NSPoint) { print("draggingSession beginAt \(screenPoint)") } //拖放鼠标移动时的代理回调 func draggingSession(_ session: NSDraggingSession, movedTo screenPoint: NSPoint) { print("draggingSession movedTo \(screenPoint)") } //结束拖放代理回调 func draggingSession(_ session: NSDraggingSession, endedAt screenPoint: NSPoint, operation: NSDragOperation) { print("draggingSession endedAt \(screenPoint)") } } I am dragging an image to the desktop through the above code, failed, help
2
0
49
2d
Inconsistent "New York" font returned between devices
I'm seeing a discrepancy in the metrics of the "New York" system font returned from various Macs. Here's a sample (works well in Playgrounds): import Cocoa let font = NSFont(descriptor: .preferredFontDescriptor(forTextStyle: .body).withDesign(.serif)!, size: NSFont.systemFontSize)! print("\(font.fontName) \(font.pointSize)") print("ascender: \(font.ascender)") let layoutManager = NSLayoutManager() print("lineHeight: \(layoutManager.defaultLineHeight(for: font))") When I run this on multiple Macs, I get two types of different results. Some – most Macs – report this: .NewYork-Regular 13.0 ascender: 12.3779296875 lineHeight: 16.0 However, when I run on my own Mac (and also on the one of a colleague), I get this instead: .NewYork-Regular 13.0 ascender: 14.034145955454255 lineHeight: 19.0 It's clearly the same font in the same point size. Yet the font has different metrics, causing a layout manager to also compute a significantly different line height. So far I've found out that neither CPU generation/architecture nor macOS version seem to play a role. This issue has been reproducible since at least macOS 14. Having just migrated to a new Mac, the issue is still present. This does not affect any other system or commonly installed font. It's only New York (aka the serif design). So I assume this must be something with my setup. Yet I have been unable to find anything that may cause this. Anybody have some ideas? Happy to file a bug report but wanted to check here first.
1
0
86
6d
NSToolbarItemGroup dynamically update subitems in toolbar
Developing on Monterey 12.7.5 I'm having trouble with updating subitems on NSToolbarItemGroup when selecting the item directly from the NSToolbar items array. I select the group item off the items array on the toolbar, and then call setSubitems: on the item, with a new array of NSToolbarItems. The group item disappears from the toolbar. It seems to leave a blank invisible item in the toolbar taking up space. I can't manually reinsert the item into the toolbar until I drag out the blank item, then drag back in the real item. Once dragged back in from the palette it displays correctly. The workaround I've come up with is to remove the item with NSToolbar removeItemAtIndex: and reinsert it with NSToollbar insertItemWithItemIdentifier:atIndex:. This works to update the subitems. Every other toolbar item property that I've tried has been able to update the item directly in the toolbar. It's only the group item's subitems that don't want to update correctly. Is there a correct way to do this that I'm missing? Calling [toolbar validateVisibleItems] didn't seem to help.
0
0
70
2d
Prevent macOS window.level floating from showing on all screens in a multi monitor setup?
I am using the window.level set to .floating as described here: https://developer.apple.com/documentation/appkit/nswindow/level The setting itself works okay. However, in a multi monitor setup, the floating window is appearing on both the screens. How can I prevent this? My users report that before macOS Sonoma, this used to not happen. Has this behaviour changed? How can I revert back to the old behaviour?
1
0
83
2d
I can't stand IOS 18 photos app
I made an account on this site for the sole reason to post this. I can not stand the IOS 18 photo app, to put it bluntly its sucks, it's made the app unusable. I was nice, I'd thought I'd give it a month or two but no, it still sucks. I wish I could uninstall IOS 18 solely cause of it. I hate the UI, its utterly unintuitive.
1
0
113
4d
Crash when setting up the content view loaded from a NIB
I am trying to understand why I am seeing crash reports for my code that creates a view from a NIB like the code below. The crash occurs when referencing contentView which should have been bound when the NIB was loaded. Am I missing something here other than checking the result of the loadNibNamed function call? class MyView: NSView { @IBOutlet var contentView: NSView! init() { super.init(frame: NSRect(x: 0, y: 0, width: 84.0, height: 49.0)) commonInit() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func commonInit() { Bundle.main.loadNibNamed("MyView", owner: self, topLevelObjects: nil) translatesAutoresizingMaskIntoConstraints = false contentView.translatesAutoresizingMaskIntoConstraints = false addSubview(contentView) contentView.frame = self.bounds }
6
0
153
1w
App was crashing in xcode 16 due to Quicklook UI framework
QLPreviewView was used in the app to display the file previews. But the following crash was happening. Date/Time: 2024-09-13 22:03:59.056 +0530 OS Version: Mac OS X 10.13.6 (17G14042) Report Version: 12 Anonymous UUID: 7CA3750A-2BDD-3FFF-5940-E5EEAE2E55F5 Time Awake Since Boot: 4300 seconds System Integrity Protection: disabled Notes: Translocated Process Crashed Thread: 0 Exception Type: EXC_CRASH (SIGABRT) Exception Codes: 0x0000000000000000, 0x0000000000000000 Exception Note: EXC_CORPSE_NOTIFY Termination Reason: DYLD, [0x1] Library missing Application Specific Information: dyld: launch, loading dependent libraries Dyld Error Message: Library not loaded: /System/Library/Frameworks/QuickLookUI.framework/Versions/A/QuickLookUI Referenced from: /private/var/folders/*/Notebook (Beta).app/Contents/MacOS/Notebook (Beta) Reason: image not found
24
4
2.3k
Sep ’24
App behavior changed under Sequoia 15.1.
I have an old Objective-C app that has been running for several years. The last compilation was in February 2024. I just upgraded to Sequoia 15.1. The app has four subviews on its main view. When I run the app only the subview that was the last one instantiated is visible. I know the other subviews are there, because a random mouse click in one invisible view causes the expected change in the visible view. What changed in 15.1 to cause this?
3
0
188
1w
[macOS Sequoia] Using RegisterEventHotkey with option and shift modifiers doesn't working anymore
Hello. In my app, I use RegisterEventHotkey to implement global keyboard shortcuts to trigger actions. Up until macOS Sequoia, I was able to use a keyboard shortcut with option and shift as the modifiers, like option shift 2 (⌥ ⇧ 2). Now, on macOS Sequoia, using RegisterEventHotkey to register a hotkey with those exact modifiers (option and shift), regardless of the key, fails with the error -9868 (eventInternalErr). Is this a documented and wanted change, or is this a bug? Other modifier keys (just command, command option, command shift, command control, control shift, etc), all work. Any insight into this would be appreciated. (Feedback filed: FB15163561) Thank you, Matthias
18
9
5.7k
Sep ’24
Possible to have NSWindow *without* NSWindowStyleMaskTitled to make the screen its on the main screen?
I have a NSWindow subclass. The window has a custom shape, and thus has a custom contentView which overrides drawRect to draw . Since the window has a custom shape it cannot use the system provided titlebar. The problem I'm having is when there are multiple screens, if my window is on the inactive screen (not mainScreen with menu bar) and I move the mouse over to the second monitor and click the window....the menu bar doesn't travel to the screen my app is on after the window is clicked. This does not happen with any other window. In all other windows, the menu bar moves to the screen once you click a window on that screen. So it appears this is because my window is not using NSWindowStyleMaskTitled. As far as I know, I can't use the system title bar and draw my custom window shape. Abandoning the custom window shape is not an option. Without going into too many details as to why I care, the menu bar really should travel with first click on my window like other apps.. Is there a way to tell the system (other than using the NSWindowStyleMaskTitled) that clicking on my window should make that screen the "main screen" (bring the menu bar over? I tried programmatically activating the application, ordering the window to the front, etc. but none of this works. This forces the user to click outside my app window, say on the desktop, to move the menu bar over, which feels wrong. Thanks in advance if anyone has any suggestions.
4
0
316
Sep ’24
App that runs fine under Xcode 15 does not work on Xcode 16.
When I upgraded to Sequoia 15.1, an app that worked fine under OS 14 stopped working. Out of 4 views on the main screen, only 1 is visible. Yet, if I click where another view should be, I get the expected action so the views are there, just not visible. Only I can't see where I am clicking! I had to upgrade to Xcode 16 to recompile the app and run it in Debug mode. When I do, I get the following: NSBundle file:///System/Library/PrivateFrameworks/MetalTools.framework/ principal class is nil because all fallbacks have failed. Can't find or decode disabled use cases. applicationSupportsSecureRestorableState FWIW - the only view that actually shows up is the last subview added to the main view.
1
0
217
1w
NSExtensionPointIdentifier key "com.apple.quicklook.preview" - which iOS versions are supported?
I am creating an iOS app to install on legacy iPads running iOS 9 and up, using XCode 13.4.1 which is the latest version that will support iOS below 11. The app is working fine but I just added a QuickLook Preview extension, and on iOS 10.3.1 it will not install due to the following error: This app contains an app extension that specifies an extension point identifier that is not supported on this version of iOS for the value of the NSExtensionPointIdentifier key in its Info.plist. Domain: com.apple.dt.MobileDeviceErrorDomain Code: -402653007 The NSExtensionPointIdentifier key in Info.plist is set by XCode automatically to "com.apple.quicklook.preview". I want to set the iOS Deployment Target to the lowest iOS version that will support this configuration. The documentation does not provide any guide as to which specific NSExtensionPointIdentifier keys are compatible with which iOS version. It just says 8+ for the whole list. Trial-and-error is limited by availability of legacy Simulators. If anyone can point to documentation that indicates which iOS is supported by which NSExtensionPointIdentifier key com.apple.quicklook.preview, I would be very grateful. Thanks (I understand about lack of App Store support etc, this is an app for my use on old iPads)
0
0
107
1w
Re-Visiting NSViewController.loadView's behaviour in 2024 and under macOS 15...
This is a post down memory lane for you AppKit developers and Apple engineers... TL;DR: When did the default implementation of NSViewController.loadView start making an NSView when there's no matching nib file? (I'm sure that used to return nil at some point way back when...) If you override NSViewController.loadView and call [super loadView] to have that default NSView created, is it safe to then call self.view within loadView? I'm refactoring some old Objective-C code that makes extensive use of NSViewController without any use of nibs. It overrides loadView, instantiates all properties that are views, then assigns a view to the view controller's view property. This seems inline with the documentation and related commentary in the header. I also (vaguely) recall this being a necessary pattern when not using nibs: @interface MyViewController: NSViewController // No nibs // No nibName @end @implementation MyViewController - (void)loadView { NSView *hostView = [[NSView alloc] initWithFrame:NSZeroRect]; self.button = [NSButton alloc...]; self.slider = [NSSlider alloc...]; [hostView addSubview:self.button]; [hostView addSubview:self.slider]; self.view = hostView; } @end While refactoring, I was surprised to find that if you don't override loadView and do all of the setup in viewDidLoad instead, then self.view on a view controller is non-nil, even though there was no nib file that could have provided the view. Clearly NSViewController has realized that: There's no nib file that matches nibName. loadView is not overridden. Created an empty NSView and assigned it to self.view anyways. Has this always been the behaviour or did it change at some point? I could have sworn that if there as no matching nib file and you didn't override loadView, then self.view would be nil. I realize some of this behaviour changed in 10.10, as noted in the header, but there's no mention of a default NSView being created. Because there are some warnings in the header and documentation around being careful when overriding methods related to view loading, I'm curious if the following pattern is considered "safe" in macOS 15: - (void)loadView { // Have NSViewController create a default view. [super loadView]; self.button = [NSButton...]; self.slider = [NSSlider...]; // Is it safe to call self.view within this method? [self.view addSubview:self.button]; [self.view addSubview:self.slider]; } Finally, if I can rely on NSViewController always creating an NSView for me, even when a nib is not present, then is there any recommendation on whether one should continue using loadView or instead move code the above into viewDidLoad? - (void)viewDidLoad { self.button = [NSButton...]; self.slider = [NSSlider...]; // Since self.view always seems to be non-nil, then what // does loadView offer over just using viewDidLoad? [self.view addSubview:self.button]; [self.view addSubview:self.slider]; } This application will have macOS 15 as a minimum requirement.
0
0
137
1w
NSTextView Contents Disappear When Ruler shown
I have a problem with rulers in an NSTextView. My code has worked fine from about Sierra (10.12), up to Ventura (13), it stopped working in Sonoma and continues to fail in the same way in Sequoia (14 - 15). When I display the ruler, the contents of the text area disappears leaving just a pale grey background. When I make the ruler invisible again the text reappears. No errors are reported (at compile or run time). I have tried adding refreshes of the text view in various places with no result. I have (for Sequoia) used Interface Builder to force the text view to use TextKit 1, also with no success. I’m at a loss as to how to proceed because I’m not getting any diagnostics, simply changed behaviour. My app provides a programming IDE. It includes a program editor that uses line numbering code for an NSTextView from WWDC/Noodlesoft. The line numbers are shown in the ruler which is sometimes visible and sometimes not. When I display the ruler, I also set the main text to not editable but removing this setting does not appear to make any difference. Any suggestions would be very wel PLATFORM AND VERSION macOS, Objective C Development environment: Xcode Version 16.0 (16A242d) [and previously Xcode 15], macOS All releases of Sonoma and Sequoia 15.0.1 (24A348) Run-time configuration: macOS Sequoia 15.0.1 (24A348) The sequence is essentially: [editTextView setEditable:NO]; [self showRulerIn:editTextView visible:YES]; Using: -(void)showRulerIn:(NSTextView*)editorTv visible:(BOOL)vis { NSScrollView *scrollV = [editorTv enclosingScrollView]; NSClipView *clipV = [scrollV contentView]; MBEditorTextView *textView = (MBEditorTextView*)[scrollV documentView]; // The actual text [scrollV setRulersVisible:vis]; // Creates the ruler if necessary … return; } LINE NUMBERING CODE The line number code comes from 2 sources but they are so similar that one must be derived from the other: Apple’s WWDC 2010 code at: https://download.developer.apple.com/videos/wwdc_2010__hd/session_114__advanced_cocoa_text_tips_and_tricks.mov Noodlesoft's code at: https://www.noodlesoft.com/blog/2008/10/05/displaying-line-numbers-with-nstextview/
2
0
175
2w
Struggling with NSScrollView
I'm still discovering swift and the various frameworks. So I'm now trying to create scrolling composition with a grid - containing images - and an NSStackView at on top. However, I'm running into a problem that might seem stupid, but when I try to wrap my NSCollectionView in another NSView and pointing the scrollView.documentView to, I can't scroll anymore... Even though it works fine when I set the scrollView.documentView to the NSCollectionView directly. Working case: override func viewDidLoad() { super.viewDidLoad() scrollView = NSScrollView(frame: .zero) scrollView.hasVerticalScroller = true scrollView.hasHorizontalScroller = false scrollView.scrollerStyle = .overlay scrollView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(scrollView) vStack = NSStackView(frame: .zero) vStack.orientation = .vertical vStack.spacing = 12 * 2 vStack.translatesAutoresizingMaskIntoConstraints = false let hStack = NSStackView() hStack.orientation = .horizontal hStack.spacing = 12 hStack.translatesAutoresizingMaskIntoConstraints = false let label1 = NSTextField(labelWithString: "Collection") hStack.addArrangedSubview(label1) let layout = PinterestLayout() layout.delegate = self collectionView = NSCollectionView(frame: .zero) collectionView.collectionViewLayout = layout collectionView.dataSource = self collectionView.delegate = self collectionView .register( ArtCardCell.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier("ArtCardCell") ) collectionView.backgroundColors = [.BG] collectionView.translatesAutoresizingMaskIntoConstraints = false // vStack.addArrangedSubview(hStack) // vStack.addArrangedSubview(collectionView) scrollView.documentView = collectionView NSLayoutConstraint.activate([ scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor), scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor), scrollView.topAnchor.constraint(equalTo: view.topAnchor), scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor), // vStack.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor), // vStack.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor), // vStack.topAnchor.constraint(equalTo: scrollView.topAnchor), // vStack.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor), // vStack.widthAnchor.constraint(equalTo: scrollView.widthAnchor), collectionView.widthAnchor.constraint(equalTo: scrollView.widthAnchor), // vStack.arrangedSubviews[0].leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 12), // vStack.arrangedSubviews[0].trailingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: -12), // vStack.arrangedSubviews[0].topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 80) ]) collectionView.postsBoundsChangedNotifications = true NotificationCenter.default.addObserver(self, selector: #selector(didScroll(_:)), name: NSView.boundsDidChangeNotification, object: collectionView.enclosingScrollView?.contentView ) } collectionView height: 3549.0 ScrollView height: 628.0 StackView height: -- Dysfunctional case: override func viewDidLoad() { super.viewDidLoad() scrollView = NSScrollView(frame: .zero) scrollView.hasVerticalScroller = true scrollView.hasHorizontalScroller = false scrollView.scrollerStyle = .overlay scrollView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(scrollView) vStack = NSStackView(frame: .zero) vStack.orientation = .vertical vStack.spacing = 12 * 2 vStack.translatesAutoresizingMaskIntoConstraints = false let hStack = NSStackView() hStack.orientation = .horizontal hStack.spacing = 12 hStack.translatesAutoresizingMaskIntoConstraints = false let label1 = NSTextField(labelWithString: "Collection") hStack.addArrangedSubview(label1) let layout = PinterestLayout() layout.delegate = self collectionView = NSCollectionView(frame: .zero) collectionView.collectionViewLayout = layout collectionView.dataSource = self collectionView.delegate = self collectionView .register( ArtCardCell.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier("ArtCardCell") ) collectionView.backgroundColors = [.BG] collectionView.translatesAutoresizingMaskIntoConstraints = false vStack.addArrangedSubview(hStack) vStack.addArrangedSubview(collectionView) scrollView.documentView = vStack NSLayoutConstraint.activate([ scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor), scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor), scrollView.topAnchor.constraint(equalTo: view.topAnchor), scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor), vStack.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor), vStack.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor), vStack.topAnchor.constraint(equalTo: scrollView.topAnchor), vStack.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor), vStack.widthAnchor.constraint(equalTo: scrollView.widthAnchor), collectionView.widthAnchor.constraint(equalTo: scrollView.widthAnchor), vStack.arrangedSubviews[0].leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 12), vStack.arrangedSubviews[0].trailingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: -12), vStack.arrangedSubviews[0].topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 80) ]) } collectionView height: 508.0 ScrollView height: 628.0 StackView height: 628.0
0
0
115
2w
How can a window be visible but not in the onscreen list?
I'm looking at a case where a handler for NSWindowDidBecomeMain gets the NSWindow* from the notification object and verifies that window.isVisible == YES, window.windowNumber > 0 and window.screen != nil. However, window.windowNumber is missing from the array [NSWindow windowNumbersWithOptions: NSWindowNumberListAllSpaces] and from CGWindowListCopyWindowInfo( kCGWindowListOptionOnScreenOnly, kCGNullWindowID ), how can that be? The window number is in the array returned by CGWindowListCopyWindowInfo( kCGWindowListOptionAll, kCGNullWindowID ). I'm seeing this issue in macOS 15, maybe 14, but not 13.
2
0
198
2w
ViewBridge to RemoteViewService Terminated (...)
After updating to Sonoma, the following is logged in the Xcode console when an editable text field becomes key. This doesn't occur on any text field, but it seems to happen when the text field is within an NSPopover or an NSSavePanel. ViewBridge to RemoteViewService Terminated: Error Domain=com.apple.ViewBridge Code=18 "(null)" UserInfo={com.apple.ViewBridge.error.hint=this process disconnected remote view controller -- benign unless unexpected, com.apple.ViewBridge.error.description=NSViewBridgeErrorCanceled} What does this mean?
4
1
653
Sep ’24
Content size of NSWindow returns zero frame after setting view on macOS 15.0 and xCode 16.1
I would like to show a nswindow at a position on screen base on height of the nswindow and its content view. I received zero width and height on macOS 15.0 and xCode 16.1 however they were returned correct width and height on previous macOS version. import Cocoa import SwiftUI class AppDelegate: NSObject, NSApplicationDelegate { private var window: NSWindow! func applicationDidFinishLaunching(_ aNotification: Notification) { window = NSWindow( contentRect: .zero, styleMask: [.miniaturizable, .closable, .resizable], backing: .buffered, defer: false) window.title = "No Storyboard Window" window.contentView = NSHostingView(rootView: ContentView()) // a swiftui view window.center() let windowFrame = window.frame print("window Frame \(windowFrame)") // print width and height zero here window.makeKeyAndOrderFront(nil) } } struct ContentView: View { var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") } .padding() } } I tried window.layoutIfNeeded() after setting contentview but it didn't work How can I get the frame after setting contentview for nswindow on macOS 15.0?
1
0
219
2w
Cocoa Binding for custom class
So I was trying to use an NSArrayController to bind the contents of a property , first I tried using NSDictionary and it worked great, here's what I did: @interface ViewController : NSViewController @property IBOutlet ArrayController * tableCities; @end ... @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; NSString* filePath = @"/tmp/city_test.jpeg"; NSDictionary *obj = @{@"image": [[NSImage alloc] initByReferencingFile:filePath], @"name": @"NYC", @"filePath": filePath}; NSDictionary *obj2 = @{@"image": [[NSImage alloc] initByReferencingFile:filePath], @"name": @"Chicago", @"filePath": filePath}; NSDictionary *obj3 = @{@"image": [[NSImage alloc] initByReferencingFile:filePath], @"name": @"Little Rock", @"filePath": filePath}; [_tableCities addObjects:@[obj, obj2, obj3]]; } @end Now for an NSPopUpButton, binding the Controller Key to the ArrayController and the ModelKeyPath to "name" works perfectly and the popupbutton will show the cities as I expected. But now, instead of using an NSDictionary I wanted to use a custom class for these cities along with an NSMutableArray which holds the objects of this custom class. I'm having some trouble going about this.
0
0
129
3w
Binding NSArrayController to an NSMutableArray not working
I have an NSMutableArray defined as a property in my ViewController class: @interface ViewController () @property NSMutableArray *tableCities; @end When the "Add" button is clicked, a new city is added: NSString* filePath = @"/tmp/city_test.jpeg"; NSDictionary *obj = @{@"image": [[NSImage alloc] initByReferencingFile:filePath], @"name": @"testCity", @"filePath": filePath}; [_tableCities addObject: obj]; Okay, this is fine, it is adding a new element to this NSMutableArray, now what I want is to somehow bind the "name" field of each city to my NSPopUpButton. So in storyboard I created an NSArrayController and tried to set its "Model Key Path" to my NSMutableArray as shown below: Then I tried to bind the NSPopUpButton to the NSArrayController as follows: but it doesn't work either, a city is added but the NSPopUpButton isn't displaying anything, what gives?
4
0
239
Oct ’24