Search code examples
swiftuimenu

Programmatically click on a menu item


var menuList = [
    UIAction(title: "title1", handler: { (action: UIAction) in self.myAction(action) }),
    UIAction(title: "title2", handler: { (action: UIAction) in self.myAction(action) }),
    UIAction(title: "title3", handler: { (action: UIAction) in self.myAction(action) }),
]

self.btn.menu = UIMenu(children: menuList)

This is a drop-down button group and I need to populate the button with the title showing the item, and the check mark next to it.

How to click on the 2nd menu item programmatically?


Solution

  • If you want the menu item to have the on state you would set state to .on

    https://developer.apple.com/documentation/uikit/uiaction/3335178-state

    menuList[1].state = .on
    

    but this is not equivalent to clicking on the menu item, you would need code in self.myAction to toggle the item's state on and off.