Sunday, 9 November 2014

Swift + Add Custom Right Bar Button Item on Navigation Bar or Add Multiple bar button on Navigation Bar in Swift

In viewDidLoad

//---   Add Custom Right Bar Button Item   ---//

            self.addRightNavItemOnView()




    func addRightNavItemOnView()
    {
        
        let buttonEdit: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
        buttonEdit.frame = CGRectMake(0, 0, 40, 40)
        buttonEdit.setImage(UIImage(named:"edit.png"), forState: UIControlState.Normal)
        buttonEdit.addTarget(self, action: "rightNavItemEditClick:", forControlEvents: UIControlEvents.TouchUpInside)
        var rightBarButtonItemEdit: UIBarButtonItem = UIBarButtonItem(customView: buttonEdit)
        
        
        
        let buttonDelete: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
        buttonDelete.frame = CGRectMake(0, 0, 40, 40)
        buttonDelete.setImage(UIImage(named:"delete.png"), forState: UIControlState.Normal)
        buttonDelete.addTarget(self, action: "rightNavItemDeleteClick:", forControlEvents: UIControlEvents.TouchUpInside)
        
        
        var rightBarButtonItemDelete: UIBarButtonItem = UIBarButtonItem(customView: buttonDelete)
        
        
        
// add multiple right bar button items       self.navigationItem.setRightBarButtonItems([rightBarButtonItemDelete, rightBarButtonItemEdit], animated: true)
        
    // uncomment to add single right bar button item
   // self.navigationItem.setRightBarButtonItem(rightBarButtonItem, animated: false)
        
    }
    
    
    func rightNavItemEditClick(sender:UIButton!)
    {
        println("rightNavItemEditClick")
    }
    
    func rightNavItemDeleteClick(sender:UIButton!)
    {
        println("rightNavItemDeleteClick")
    }


2 comments:

  1. Hi, Sharma. Thanks for this, and I have tried this, but my nav bar shows nothing of multiple bar buttons. I've checked my viewdidload, everything looks fine as above, but to no avail. Quite curious. : (

    ReplyDelete
    Replies
    1. You need the images "delete.png" and "edit.png" bcuz its custom button

      buttonEdit.setImage(UIImage(named:"edit.png"), forState: UIControlState.Normal)
      buttonDelete.setImage(UIImage(named:"delete.png"), forState: UIControlState.Normal)

      Delete