Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Notification when NSPopupButton changes its value in cocoa XCode5

I want to know if is it a method different to

-(void)menu:(NSMenu *)menu willHighlightItem:(NSMenuItem *)item

and

-(void)menuDidClose:(NSMenu *)menu

to help me to know when NSPopupButton's selected value changes (for example by pressing a key name instead of selecting it from the NSMenu)

like image 580
Jesus Avatar asked Aug 28 '14 17:08

Jesus


2 Answers

first create your IBAction:

- (IBAction)mySelector:(id)sender {
    NSLog(@"My NSPopupButton selected value is: %@", [(NSPopUpButton *) sender titleOfSelectedItem]);
}

and then assign your IBAction to your NSPopupButton

    [popupbutton setAction:@selector(mySelector:)];
    [popupbutton setTarget:self];
like image 162
Jesús Ayala Avatar answered Nov 15 '22 08:11

Jesús Ayala


Combine solution (works only on iOS 13 and above)

I tried observing indexOfSelectedItem property of NSPopupButton but realised it is not KVO compatible.

Now since NSPopupButton internally uses NSMenu, I tried to find relevant notifications that NSMenu sends and found that NSMenu.didSendActionNotification can be used.

import Combine

extension NSPopUpButton {

    /// Publishes index of selected Item
    var selectionPublisher: AnyPublisher<Int, Never> {
        NotificationCenter.default
            .publisher(for: NSMenu.didSendActionNotification, object: menu)
            .map { _ in self.indexOfSelectedItem }
            .eraseToAnyPublisher()
    }
}

This extension publishes index whenever there user makes any selection in NSPopupButton.

It can be used as follows

popupButton.selectionPublisher
    .sink { (index) in
        print("Selecion \(index)")
    }
    .store(in: &storage)
like image 26
Kaunteya Avatar answered Nov 15 '22 06:11

Kaunteya