Sunday, 9 November 2014

Swift + Add Custom Left Bar Button Item on Navigation Bar

 In View Did Load

//---   Add Custom Left Bar Button Item   ---//

        self.addLeftNavItemOnView()



    func addLeftNavItemOnView ()
    {

       // hide default navigation bar button item
        self.navigationItem.leftBarButtonItem = nil;
        self.navigationItem.hidesBackButton = true;
        
        
        let buttonBack: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
        buttonBack.frame = CGRectMake(0, 0, 40, 40)
        buttonBack.setImage(UIImage(named:"ImageName.png"), forState: UIControlState.Normal)
        buttonBack.addTarget(self, action: "leftNavButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        
        var leftBarButtonItem: UIBarButtonItem = UIBarButtonItem(customView: buttonBack)
        
        self.navigationItem.setLeftBarButtonItem(leftBarButtonItem, animated: false)
        
        
    }
    
    func leftNavButtonClick(sender:UIButton!)
    {
        self.navigationController?.popViewControllerAnimated(true)
    }

3 comments:

  1. Thanks Naveen, I was trying the similar solution from 2 days but it wasn't successful, I don't know right now how but by adding following two lines from your code it worked for me.

    self.navigationItem.leftBarButtonItem = nil;
    self.navigationItem.hidesBackButton = true;

    ReplyDelete
  2. You just saved my bacon...been on this hoohar for 4 days now!! THANKS ;-)

    ReplyDelete
  3. Does not compile any more, use
    let buttonBack: UIButton = UIButton(type: UIButtonType.Custom) as UIButton

    ReplyDelete