NSPopupButton在cocoa XCode5中更改其值时的通知

时间:2014-08-28 17:52:09

标签: macos cocoa xcode5.1 nspopupbutton

我想知道它是否是一种与

不同的方法
-(void)menu:(NSMenu *)menu willHighlightItem:(NSMenuItem *)item

-(void)menuDidClose:(NSMenu *)menu

帮助我知道NSPopupButton的选定值何时发生变化(例如,通过按键名而不是从NSMenu中选择它)

2 个答案:

答案 0 :(得分:11)

首先创建您的IBAction:

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

然后将您的IBAction分配给您的NSPopupButton

    [popupbutton setAction:@selector(mySelector:)];
    [popupbutton setTarget:self];

答案 1 :(得分:0)

组合解决方案(仅适用于 iOS 13 及更高版本)

我尝试观察 NSPopupButton 的 indexOfSelectedItem 属性,但意识到它与 KVO 不兼容。

现在由于NSPopupButton内部使用了NSMenu,我尝试查找NSMenu发送的相关通知,发现可以使用NSMenu.didSendActionNotification

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()
    }
}

每当用户在 NSPopupButton 中进行任何选择时,此扩展都会发布索引。

可以如下使用

popupButton.selectionPublisher
    .sink { (index) in
        print("Selecion \(index)")
    }
    .store(in: &storage)
相关问题