Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically set action for barButtonItem in swift 3?

Here is what I used previously,

var barButtonItem = UIBarButtonItem(image: backImgs, style: UIBarButtonItemStyle.plain, target: self, action: Selector("menuButtonTapped:"))

But there is some syntax changes for Swift 3.

like image 221
Bhanupriya Avatar asked Sep 29 '16 11:09

Bhanupriya


4 Answers

ex:-

navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add", style: .plain, target: self, action: #selector(addTapped))
like image 163
Tony Vincent Avatar answered Nov 19 '22 08:11

Tony Vincent


Summarize the mostly used method in Swift 3 for adding action to a barButton.

  1. Barbutton with text

    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add", style: .plain, target: self, action: #selector(addTapped))
    
  2. BarButton with your own image

    navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named:"add"), style: .plain, target: self, action: #selector(addTapped))
    
  3. BarButton with system image

    navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addTapped))
    
like image 23
flame3 Avatar answered Nov 19 '22 08:11

flame3


If anyone is using customView:

barButtonItem.customView?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onBarButtonItemClicked)))
like image 38
Onuray Sahin Avatar answered Nov 19 '22 06:11

Onuray Sahin


You just need to change your selector syntax as of from Swift 3 you need to specify the first parameter name of method in your function call so change your selector like this.

#selector(menuButtonTapped(sender:))

And your method should be like this.

func menuButtonTapped(sender: UIBarButtonItem) {

}
like image 14
Nirav D Avatar answered Nov 19 '22 08:11

Nirav D