I hope this开发者_开发百科 isn't too general. I'm a beginner and I'm trying to learn how to make a Status Bar (menu on the right side) for Mac in Objective-C.
I've managed to create the basic outline, but I don't know what the method to use for a particular action: I would like when the drop-down menu appears for it to call a method that will return the string to be displayed.
In other words, how do I make the menu call a method and display its return value.
In cocoa please.
Thanks!
You create an IBAction method. Any method labelled as such will be seen by the controller of the class in Interface Builder. So if you put such a method in your app controller class, then in interface builder you will see the method in your app controller object. Now that you can see it in IB, you connect that method to the menu item by control-dragging from the menu item to the controller. An ibaction method has an argument called "sender" which is the sender of the message. So if you hook the method to the menu item then the sender will be the NSMenuItem because that's the object that calls the method. And an NSMenuItem responds to the "setTitle:" method which you can use to change the title. So something like this would work...
In ".h" file
-(IBAction)displayMenuItemtitle:(id)sender;
In ".m" file
-(IBAction)displayMenuItemtitle:(id)sender {
NSString* newTitle = @"my new title";
[sender setTitle:newTitle];
}
EDIT: After re-reading your question maybe you want the NSMenu object to display the new title when the menu it about to open. NSMenu has a delegate method menuWillOpen:. So set your app controller to be the delegate of the NSMenu. Then in your appcontroller class use this...
- (void)menuWillOpen:(NSMenu *)menu {
NSArray* menuItems = [menu itemArray];
NSMenuItem* theMenuItem = [menuItems objectAtIndex:0];
NSString* newTitle = @"my new title";
[theMenuItem setTitle:newtitle];
}
精彩评论