in iOS 14, there are new APIs for UIMenu
, and it can now be attached to UIBarButtonItem
, just like that:
This is my code:
@IBOutlet weak var addButton: UIBarButtonItem! // The button is from the storyboard.
override func viewDidAppear(_ animated: Bool) {
if #available(iOS 14.0, *) {
let simpleAction : UIAction = .init(title: "Simple", image: nil, identifier: nil, discoverabilityTitle: nil, attributes: .init(), state: .mixed, handler: { (action) in
self.addButtonActionPressed(action: .simple)
})
let advancedAction : UIAction = .init(title: "Advanced", image: nil, identifier: nil, discoverabilityTitle: nil, attributes: .init(), state: .mixed, handler: { (action) in
self.addButtonActionPressed(action: .advanced)
})
let actions = [simpleAction, advancedAction]
let menu = UIMenu(title: "", image: nil, identifier: nil, options: .displayInline, children: actions)
addButton.primaryAction = nil
addButton.menu = menu
}
}
But the problem is, that when I press the button, nothing happen. Only when I long-press the button, it shows the menu. I've seen this code on the internet:
button.showsMenuAsPrimaryAction = true
But it won't help me, because Value of type 'UIBarButtonItem' has no member 'showsMenuAsPrimaryAction'
Any ideas how to fix? I'm using Xcode 12.0 beta 4 (12A8179i).
I fixed this issue I had. If it's happening to any of you, this what you can do:
Try to check if there is any other action to the button. If there is, it won't show the menu as the primary action.
If you are using storyboard, use code instead, for example:
self.navigationItem.rightBarButtonItem = .init(systemItem: .add)
// Then configure the menu of the item here, by doing:
navigationItem.rightBarButtonItem!.menu = menu
// Replace 'menu' with your menu object.
If there are any other tips you know, feel free to edit this question and add them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With