Gerardo Torres
Gerardo Torres

Reputation: 81

Swift UIBarButtonItem add Gesture Recognizer

I want to add a long press Gesture Recognizer to a UIBarButtonItem, but I can't. There is no possibility using the Storyboard, nor is there a method addGestureRecognizer in UIBarButtonItem.

How can I solve this problem?

Upvotes: 2

Views: 2160

Answers (2)

cyanide
cyanide

Reputation: 3964

Didn't work with UIButton (iOS 12), however works with UILabel:

let backButtonView = UILabel()
backButtonView.isUserInteractionEnabled = true
backButtonView.text = "x"
backButtonView.sizeToFit()
backButtonView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onBackButtonClick(_:))))
backButtonView.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(onBackButtonLongPress(_:))))
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButtonView)

Upvotes: 1

PongBongoSaurus
PongBongoSaurus

Reputation: 7385

You can try the following method:

    //1. Create A UIButton Which Can Have A Gesture Attached
    let button = UIButton(type: .custom)
    button.frame = CGRect(x: 0, y: 0, width: 80, height: 40)
    button.setTitle("Press Me", for: .normal)

    //2. Create The Gesture Recognizer
    let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(doSomething))
    longPressGesture.minimumPressDuration = 1
    button.addGestureRecognizer(longPressGesture)

    //3. Create A UIBarButton Item & Initialize With The UIButton
    let barButton = UIBarButtonItem(customView: button)

    //4. Add It To The Navigation Bar
    self.navigationItem.leftBarButtonItem = barButton

Of course the Selector method would be replaced with your own method.

Upvotes: 2

Related Questions