1

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?

clemens
  • 16,716
  • 11
  • 50
  • 65
  • See https://stackoverflow.com/questions/32517434/ios-swift-how-to-implement-longpressed-action-for-backbutton for one possible idea. – rmaddy Nov 09 '17 at 04:50

2 Answers2

2

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.

BlackMirrorz
  • 7,217
  • 2
  • 20
  • 31
1

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)
cyanide
  • 3,885
  • 3
  • 25
  • 33