swiftuibarbuttonitemios14uimenu

Show UIMenu when single-tapping UIBarButtonItem


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).


Solution

  • I fixed this issue I had. If it's happening to any of you, this what you can do:

    If there are any other tips you know, feel free to edit this question and add them.