Search code examples
iosswiftuimenucontrolleruimenuitem

Disable the flickering/blinking of UIMenuItems in UIMenuController in Swift


How can I get rid of the flickering/blinking of UIMenuItems in a UIMenuController? I currently have copy and paste items, but when my app displays the menu inside the action of a UILongPressGestureRecognizer, they start blinking.

@objc func viewLongPressed(_ recognizer: UILongPressGestureRecognizer) {
    [...]

    UIMenuController.shared.setMenuVisible(true, animated: true)
}

Are there any implementations for this in iOS?


Solution

  • This is because UILongPressGestureRecognizer events get recognized constantly if you keep pressing the recognizer view. Calling the setMenuVisible(animated:) method of UIMenuController repeatedly causes the blinking effect you've described.

    To solve this, show the menu only if the state of the recognizer is .began.

    @objc func viewLongPressed(_ recognizer: UILongPressGestureRecognizer) {
        [...]
    
        if recognizer.state == .began {
            UIMenuController.shared.setMenuVisible(true, animated: true)
        }
    }