How do I set the title on the destination view controller during prepareForSegue:

Steve Moser picture Steve Moser · Jul 22, 2013 · Viewed 9.1k times · Source

I want to simply set the title on my destination view controller so that it shows in its navigation controller's navigation bar in the prepareForSegue: method however setting its title or navigationItem like so:

[segue.destinationViewController setTitle:@"doesn't work"]; [segue.destinationViewController.navigationItem setTitle:@"this either"];

doesn't work possibly because the destination's view controller's view isn't loaded yet. Can I do this without creating a custom destination view controller?

Answer

Julian Vogels picture Julian Vogels · Jul 22, 2013

Try accessing your ViewController that is embedded in the UINavigationController like this. First you give your segue an identifier in the interface builder, then you access the segue in the prepareForSegue method and set the title by accessing the topViewController property of the navigation controller you segue to.

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString:@"yourSegueIdentifier"]) {
        UINavigationController *navController = 
           (UINavigationController*)[segue destinationViewController];
        YourViewController *destViewController = 
           (YourViewController* )[navController topViewController];

        destViewController.navgationItem.title.text = @"Your new title";
    }
}