Search code examples
iosobjective-cuinavigationitempushviewcontroller

Make left bar button's title of navigation item the same as previous view's title


In my 1st VC(postVC), I have below code to set navigation bar title varied to username:

// Set nav bar items.
[self.navigationController setNavigationBarHidden:NO animated:NO];
NSString *title = [NSString stringWithFormat:@"@%@'s Posts",[userPassed username]];
self.navigationItem.title = title;

However, there is a little problem here that when I call 2nd VC(detailVC) by this method (push VC), the left bar button item's title in the 2nd VC is shown "back" but I expect its title to follow the title in previous VC(1st VC).

- (void) didSelectItemFromCollectionView:(NSNotification *)notification
{
    NSDictionary *cellData = [notification object];
    if (cellData)
    {
        if (!self.detailViewController)
        {
            self.detailViewController = [[PAWUserPostsDetailViewController alloc] initWithNibName:@"PAWUserPostsDetailViewController" bundle:nil];
        }
    self.detailViewController.detailItem = cellData;
    [self.navigationController pushViewController:self.detailViewController animated:YES];
    }
}

If I change

 self.navigationItem.title = @"test";

it works as expected. In 2nd VC, left bar button item's title is shown "test" as I want. So, to be clear, my question is how to make left bar button item's title follow the title of previous VC which is varied by username.


Solution

  • In postVC.h file

    @property (strong, nonatomic)NSString*title;
    

    In postVC.m file

    title = [NSString stringWithFormat:@"@%@'s Posts",[userPassed username]];
    self.navigationItem.title = title;
    self.detailViewController.newtitle=self.title; 
    [self.navigationController pushViewController:self.detailViewController animated:YES];
    

    In detailVC.h file

      @property (strong, nonatomic) NSString*newtitle;
    

    In detailVC.m file

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:newtitle style:UIBarButtonItemStylePlain target:self action:@selector(back:)];