Add action to UIBarButtonItem Swift

14.6k views Asked by At

Button is created in storyboard and I want to add an action.

self.cancel.action = NSSelectorFromString("cancel:")

func cancel(sender: UIBarButtonItem) ->() {
}

This not working. Thanks

4

There are 4 answers

0
Alvin George On BEST ANSWER

See mine.

  1. Adding a UIButton to UIBarbuttonitem.

    self.navigationController?.navigationBarHidden = false
    
    //making a button
    var button: UIButton = UIButton()
    button.setImage(UIImage(named: "person-icon.jpg"), forState: .Normal)
    button.frame = CGRectMake(0, 0, 25, 25)
    button.targetForAction("actioncall", withSender: self)
    button.addTarget(self, action: "actioncall", forControlEvents: UIControlEvents.TouchUpInside)
    
    //making a UIBarbuttonItem on UINavigationBar
    var rightItem:UIBarButtonItem = UIBarButtonItem()
    rightItem.customView = button        
    self.navigationItem.rightBarButtonItem = rightItem
    
  2. Initialise a UIBarButtonItem

    let rightNavItem = UIBarButtonItem(image: UIImage(named: "search1x"), landscapeImagePhone: nil, style: UIBarButtonItemStyle.Plain, target: self, action: "actioncall")
    navigationItem.rightBarButtonItem = rightNavItem
    
  3. OR

    let rightNavItem = UIBarButtonItem()
    rightNavItem.action = "action call"
    
    
    //Anticipated Method on clicking uibarbuttonitem
    func actioncall(){
    }
    
4
Mundi On

Just create a function in your swift class like the following

@IBAction func cancel() {
   // your code
}

And connect it in storyboard by ctrl-dragging from the button to your view controller.

0
93sauu On
@IBAction func action() {
   // your code
}       

   var button   = UIButton.buttonWithType(UIButtonType.System) as UIButton
   button.frame = CGRectMake(100, 100, 100, 50)
   button.backgroundColor = UIColor.greenColor()
   button.setTitle("Button", forState: UIControlState.Normal)
   button.addTarget(self, action: "action", forControlEvents: UIControlEvents.TouchUpInside)
   self.view.addSubview(button)
0
Rupal Chawla On

Or if selector is in a different class

let barBtn = UIBarButtonItem(title: nil, style: UIBarButtonItemStyle.Plain, target: self, action: #selector(CustomToolbarItemsClass.testSelector))


//This is in CustomToolbarItemsClass class
@objc static func testSelector(){
 print("Hello!")
}