Search code examples
iosswift2xcode7rightbarbuttonitem

performSegue with programmatically added Navigation button


I am trying to customize a Navigation bar button item programmatically... I am just having some issues here which I am sure is an easy fix. I want to make it the default Add button for now, but also in the future will want to make the bar button item a custom icon I create. so I guess I would like to know both ways how to programmatically change a navigation bar button to default styles and custom icons...thanks!

override func viewDidAppear(animated: Bool) {

    let rightbutton = UIBarButtonItem(title: "+", style: UIBarButtonItemStyle.Plain, target: self, action: "uploadButtonClicked")

    navigationItem.rightBarButtonItem = rightbutton


}

Solution

  • Here is how you would do it with the default add button:

        let button = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "uploadButtonClicked")
        self.navigationItem.rightBarButtonItem = button
    

    Here is how you would programmatically add a custom image:

        let customImage = UIImage(named: "customButtonImage")
        let customButton = UIBarButtonItem(image: customImage, style: UIBarButtonItemStyle.Plain, target: self, action: "uploadButtonClicked:")
        self.navigationItem.rightBarButtonItem = customButton
    

    To perform the segue, you can do this:

    @IBAction func uploadButtonClicked(sender: UIBarButtonItem) {
        performSegueWithIdentifier("segueIdentifier", sender: self)
    }
    

    Or, if you want to go to another storyboard from there, then your IBAction will look like this:

    @IBAction func uploadButtonClicked(sender: UIBarButtonItem) {
        let storyboard = UIStoryboard(name: "YourStoryboard", bundle: nil)
        let nc = storyboard.instantiateInitialViewController() as! UINavigationController
        let vc = nc.viewControllers.first as! YourViewController