iOS how do I detect when a IUButton with showMenuAsPrimaryAction is beginning to present the menu?

55 Views Asked by At

I have a UIButton with the menu set to a UIMenu (with chidren) and ShowMenuAsPrimaryAction set to true.

but I would like to know when the button is pressed and the menu is about to be presented so I can stop other UITextFields from being FirstResponder?

Regards Christian Arild Stœr Andersen

1

There are 1 best solutions below

2
son On

I think you can definitely determine it with contextMenuInteraction:

class MenuButton: UIButton {

    var onDismissMenu: (() -> Void)?
    var onShowMenu: (() -> Void)?

    override func contextMenuInteraction(_ interaction: UIContextMenuInteraction, willEndFor configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionAnimating?) {
        super.contextMenuInteraction(interaction, willEndFor: configuration, animator: animator)

        onDismissMenu?()
    }

    override func contextMenuInteraction(_ interaction: UIContextMenuInteraction, willDisplayMenuFor configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionAnimating?) {
        super.contextMenuInteraction(interaction, willDisplayMenuFor: configuration, animator: animator)

        onShowMenu?()
    }
}

Then handle onShowMenu to hide the keyboard, something like:

button.onShowMenu = { [weak self] in
    self?.view.endEditing(true)
}

Output:

enter image description here