Instantly share code, notes, and snippets.
Created
October 23, 2022 00:09
macOS 11-compatible Mac Catalyst PopUp Button (Private API)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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