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)