I am new to Swift 3. Currently, I have a UIBarButtonItem. How to make this button action to be triggered only when it is pressed for multiple times? For example, a ViewController will only appear when user pressed this button twice.
3 Answers
1
votes
Create custom view for UIBarButtonItem
and add UITapGestureRecognizer
for the custom view and set the numberOfTapsRequired
property value as 2
Sample code :
class viewController: UIViewController {
var doubleTapGesture: UITapGestureRecognizer!
var barButton: UIBarButtonItem!
var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
button = UIButton(type: .custom)
button.setTitle("title", for: .normal)
button.frame = CGRect(x: 0, y: 0, width: 64, height: 30)
doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(viewController.buttonClicked))
doubleTapGesture.numberOfTapsRequired = 2
button.addGestureRecognizer(doubleTapGesture)
barButton = UIBarButtonItem(customView: button);
navigationItem.rightBarButtonItem = barButton
}
func buttonClicked() {
// Method for UITapGestureRecognizer
}
}
1
votes
0
votes
Just add UITapGestureRecognizer to your UIBarButtonItem like below.
func addBarButton() -> UIBarButtonItem
{
let btnImage = UIImage(named: "imageName")!
let imageButton : UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 25, height: 25))
imageButton.setBackgroundImage(btnImage, for: UIControlState())
let doubleTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.buttonAction(_:)))
doubleTap.numberOfTapsRequired = 2
imageButton.addGestureRecognizer(doubleTap)
return UIBarButtonItem(customView: imageButton)
}
call bellow line from your viewDidLoad function.
navigationItem.rightBarButtonItems = [addBarButton()]