【问题标题】:Notification when NSPopupButton changes its value in cocoa XCode5NSPopupButton 在可可 XCode5 中更改其值时的通知
【发布时间】:2014-08-28 17:52:09
【问题描述】:
我想知道是不是和
不同的方法
-(void)menu:(NSMenu *)menu willHighlightItem:(NSMenuItem *)item
和
-(void)menuDidClose:(NSMenu *)menu
帮助我了解 NSPopupButton 的选定值何时发生变化(例如,通过按一个键名而不是从 NSMenu 中选择它)
【问题讨论】:
标签:
macos
cocoa
xcode5.1
nspopupbutton
【解决方案1】:
首先创建您的 IBAction:
- (IBAction)mySelector:(id)sender {
NSLog(@"My NSPopupButton selected value is: %@", [(NSPopUpButton *) sender titleOfSelectedItem]);
}
然后将您的 IBAction 分配给您的 NSPopupButton
[popupbutton setAction:@selector(mySelector:)];
[popupbutton setTarget:self];
【解决方案2】:
组合解决方案(仅适用于 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)