Reputation: 21966
I am training myself with an application that has a navigation controller, and the user can switch between two view controllers.
The root view controller class is called ViewController, and that's how I programmatically add the navigation controller in my app delegate:
self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
navController= [[UINavigationController alloc]initWithRootViewController: viewController];
self.window.rootViewController= navController;
This is navController:
@property (strong, nonatomic) UINavigationController* navController;
The second view controller is called SecondViewController.I push it whenever the user clicks on the bar button item:
self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithTitle: @"Second View" style: UIBarButtonItemStylePlain target: self action: @selector(switchView:)];
This is the selector executed:
- (void) switchView : (id) sender
{
if(!nextController)
{
nextController= [[SecondViewController alloc]initWithNibName: @"SecondViewController" bundle: nil];
}
[self.navigationController pushViewController: nextController animated: YES];
}
Then in the second view controller appears automatically a button with the title "back", that switches to the first view.That's fine to me, but I would like to set the title and the style.So I'm trying to change the title:
self.navigationItem.backBarButtonItem.title= @"First View";
But nothing to do, the title is still "back", how do I change it?
Also, ain't I following a wrong or unefficient approach, right?
Upvotes: 0
Views: 1444
Reputation: 960
If you set the title
property of your ViewController
class in viewDidLoad
, that string will appear as the text of your back button when you push a SecondViewController
onto the stack.
Upvotes: 2
Reputation: 2211
Try this for changing the button title. Init and add your own leftBarButtonItem and hide the stock back button.
UIBarButtonItem* backBtn = [[UIBarButtonItem alloc] initWithTitle:@"BUTTON_NAME" style:UIBarButtonItemStyleDone target:self action:@selector(backAction)];
self.navigationItem.leftBarButtonItem = backBtn;
self.navigationItem.hidesBackButton = YES;
You're going to want to hide the original back button if you can and just make a backAction which can be something that uses the popViewcontrollerAnimated function (if you pushed the viewcontroller on to begin with).
- (void) backAction {
[self.navigationController popViewControllerAnimated:YES];
}
Upvotes: 1