Associating an Image with NSPopupbutton by NSArrayController

This question is an extension of the link (The question in the link is mainly aimed at binding NSPopupbutton to NSArrayController)

I have a Person class with NSString *name and NSImage *avatar properties
I have to show all the names of people in the Popup button, as shown in the image below. enter image description here

But now that the demand has changed, I also need to show the avatar of the person.
How to use Cocoa bindings to associate a personal avatar with an NSPopup button so that it looks like the picture above for the match (last menu option)


Note. Michael was temporarily added for demonstration using the following code:

 person.title = @"Michael"; person.image = [NSImage imageNamed:@"avatar.png"]; [_popupButton.menu addItem:person]; 
+7
objective-c cocoa appkit cocoa-bindings macos
source share
1 answer

There are two ways to achieve this: -

First, take the table view on the cell inside that there are two columns, one for the image cell, and the second for the text cell. Fill the table through the bindings, and then add your table view inside your popup button as follows: -

 NSMenu *theMenu = [[NSMenu alloc] initWithTitle:@""]; NSMenuItem *Item = [[NSMenuItem alloc] initWithTitle:@"NameList" action:NULL keyEquivalent:@""]; [Item setView:self.tableVw]; [theMenu addItem:Item]; [self.popUptn setMenu:theMenu]; 

Then follow these simple steps: -

Assuming your array contains name elements.

1) Select the binding of arrayContoller to FileOwner's and ModelKeyPath->array .

2) Select PopUpButton inside the binding Inspector->Selected Object bind to FileOwner's and ModelKeyPath->yourString . This will select the desired name accordingly.

3) Select PopUpButton inside binding Inspector->Content Values and ModelKeyPath->array

4) Now for installing image inside PopUpButton see below code: -

 NSMenuItem *menuItm=[self.popUpBtn itemWithTitle:@"Michael"]; [menuItm setImage:[NSImage imageNamed:@"dot.gif"]]; 

Edit: -

1) In the first method, your text and image are filled by binding only you need to add this tableview inside your popupbutton.

2) In the second method, your popupbutton will display an image for the name, but programmatically. And also, if you want to display images for all names, then use the for loop to set the images inside the menu item.

0
source share

All Articles