Search code examples
iosuiviewcontrolleruinavigationcontrollersegueuinavigationitem

Back button title on custom "Replace" Segue


I have a custom "Replace" segue that replaces the current viewcontroller with another. This works good. However the back button title always becomes "Back". The segue works like this:

ViewController A -> ViewController B

ViewController B then performs a replace segue to ViewController C. The stack is then:

ViewController A -> ViewController C

This is the code for ReplaceSegue.swift:

public class ReplaceSegue: UIStoryboardSegue
{
    public var animated = true

    public override func perform()
    {
        let navigationController: UINavigationController = sourceViewController.navigationController!

        var controllerStack = navigationController.viewControllers
        let index = controllerStack.indexOf(sourceViewController)
        controllerStack[index!] = destinationViewController

        navigationController.setViewControllers(controllerStack, animated: animated)
    }
}

And for my ViewController:

func replaceAgendaViewController()
{
    let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let agendaViewController = mainStoryboard.instantiateViewControllerWithIdentifier("AgendaViewController") as! AgendaViewController
    let segue = ReplaceSegue(identifier: replaceSegueId, source: self, destination: agendaViewController) { () -> Void in

    }
    segue.animated = false
    segue.perform()
}

Have tried this code but I understand why it does not work as it sets the navigationItem on the ViewController that is replaced:

navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: UIBarButtonItemStyle.Plain, target: nil, action: nil) 

I also do not want to set the back button title previous to performing the segue as the ViewController contains other segues that may not want that back button title. Any suggestions?


Solution

  • It was quite easy to fix, I just added the code to the prepareForSegue:sender: in ViewController A:

    public override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
    {
        switch (segue.identifier!) {
        case agendaSegueId:
            navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: UIBarButtonItemStyle.Plain, target: nil, action: nil) 
            ...
        }
    }