iosuikituibuttonuimenu

UIButton menu actions are backwards


Here's a small demo app that configures a button in the interface:

class ViewController: UIViewController {
    @IBOutlet var button: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        var actions = [UIAction]()
        for title in ["One", "Two", "Three"] {
            let action = UIAction(title: title) { action in print(action.title) }
            actions.append(action)
        }
        let menu = UIMenu(title: "", children: actions)
        button.menu = menu
    }
}

The button referred to in the outlet is already set to show its menu as its primary action.

Okay, so I run the app and tap the button, and this is what I see:

button displaying menu

It's backwards! I can debug and see that the button's menu does have its actions in the right order ("One" comes first), so why is the menu appearing in reverse order? Is this some sort of UIKit bug?

This is with Xcode 16.4, iOS 18.5.


Solution

  • This is the automatic behavior of the menu, but you can force the order:

    button.preferredMenuElementOrder = .fixed
    

    ⚠️ Note that you should apply this on the button, NOT the menu itself!