how to programmatically set action for barButtonIt

2019-01-31 12:31发布

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. Thanks in advance.

10条回答
趁早两清
2楼-- · 2019-01-31 12:32

for Swift 4 add in viewDidLoad:

navigationItem.rightBarButtonItem = UIBarButtonItem(
    barButtonSystemItem: UIBarButtonSystemItem.add, 
    target: self, 
    action: #selector(addTransaction)
)
查看更多
forever°为你锁心
3楼-- · 2019-01-31 12:34

ex:-

navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add", style: .plain, target: self, action: #selector(addTapped))
查看更多
不美不萌又怎样
4楼-- · 2019-01-31 12:37

One line of code on Swift 3 for iOS 10.1:

navigationController?.navigationBar.topItem?.rightBarButtonItem = UIBarButtonItem(title: "Add", style: .plain, target: self, action: nil)
查看更多
ら.Afraid
5楼-- · 2019-01-31 12:39

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) {

}
查看更多
Root(大扎)
6楼-- · 2019-01-31 12:41

Make a UIBarButtonItem:

let rightButton: UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.done, target: self, action: #selector(LocationViewController.doneButtonClicked(_:)))

Add to NavigationItem:

self.navigationItem.rightBarButtonItem = rightButton

Associated function:

func doneButtonClicked(_ button:UIBarButtonItem!){    
    print("Done clicked")    
}
查看更多
Bombasti
7楼-- · 2019-01-31 12:43

If anyone is using customView:

barButtonItem.customView?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onBarButtonItemClicked)))
查看更多
登录 后发表回答