Search code examples
iosswiftuinavigationbaruibarbuttonitem

How to detect longpress in BarButtonitem


I have a UIBarButtonItem in navigation bar. When a user clicks it, it pops to another viewController. Now i want that when user long-press on that button (navigation bar button) I want to show a help message. I want help to detect the onlick event and longpress event separately.


Solution

  • so I found that UIBarButton has not property like longpress so all I do is take a UIButton give it longpress gesture and add that UIButton in navigation bar as UIBarButtonItem.

    I hope it will helpful for someone else who is facing same problem.

            let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
            btn.backgroundColor = .green
            
            let gesture = UILongPressGestureRecognizer(target: self, action: #selector(longpress))
            btn.addGestureRecognizer(gesture)
            
            let barbtn = UIBarButtonItem(customView: btn)
            self.navigationItem.rightBarButtonItem = barbtn
    

    thank you :)