Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save steventroughtonsmith/68a554986da979fb73d4f72ee416bc1e to your computer and use it in GitHub Desktop.
Save steventroughtonsmith/68a554986da979fb73d4f72ee416bc1e to your computer and use it in GitHub Desktop.
macOS 11-compatible Mac Catalyst PopUp Button (Private API)
class PSTLMacOS11AwarePopUpButton: UIButton {
var selectedPopUpIndex = 0 {
didSet {
sendActions(for: .valueChanged)
}
}
override var menu: UIMenu? {
set {
/* Button title must match first menu item */
setTitle(newValue?.children.first?.title, for: .normal)
super.menu = newValue
}
get {
super.menu
}
}
convenience init() {
self.init(type: .system)
showsMenuAsPrimaryAction = true
if #available(iOS 15.0, *) {
changesSelectionAsPrimaryAction = true
}
}
override func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
preparePopUpButtonForMacOS11()
}
func preparePopUpButtonForMacOS11() {
guard ProcessInfo.processInfo.operatingSystemVersion.majorVersion < 12 else { return }
if let NSPopupButton = value(forKeyPath: "_visualElement._button") as? NSObject {
guard NSPopupButton.responds(to: NSSelectorFromString("setPullsDown:")) else { return }
NSPopupButton.setValue(false, forKey: "pullsDown")
if let NSMenu = NSPopupButton.value(forKeyPath: "menu") as? NSObject {
NotificationCenter.default.addObserver(forName: NSNotification.Name("NSMenuDidSendActionNotification"), object: NSMenu, queue: nil) { note in
guard let indexOfSelectedItem = NSPopupButton.value(forKeyPath: "indexOfSelectedItem") as? Int else { return }
DispatchQueue.main.async {
self.selectedPopUpIndex = indexOfSelectedItem
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment