How do I change the back button on a UINavigationC

2019-06-09 05:09发布

In the view I want to change it for I have the following code but it fails.

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //Logout button
    UIBarButtonItem * logout = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(goBack)];
    logout.title = @"Logout";
    nav_delegate.navigationController.navigationItem.leftBarButtonItem = logout;
    [logout release];
}

Thank you for any help.

3条回答
做个烂人
2楼-- · 2019-06-09 05:30

Implementing backBarButtonItem is for the super view controller which uses pushViewController:subViewController.

For example, if you've pushed a view controller for its super view controller Logout:

[self.navigationController pushViewController:subViewController animated:YES];

Then, you should've implemented backBarButtonItem in the super view, which is Logout view, NOT in the pushed subViewController.

So, to implement backBarButtonItem, you do it in super view Logout, like:

self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:logoutViewTitle style:UIBarButtonItemStyleBordered target:nil action:nil];

You can do this in -(void)viewDidLoad for static use, or in -(void)viewWillAppear:(BOOL)animated for dynamic use, for setting the title without allocating and initializing.

One more tip: In interface builder, there is input field for backBarButtonItem title. But if you didn't enter, you must allocate and initialize the backBarButton with title in .m files, like the code above. If you've entered the title for static use, I believe you can change it simply by using:

[self.navigationItem.backBarButtonItem setTitle:logoutViewTitle];

Hope it helped.

查看更多
闹够了就滚
3楼-- · 2019-06-09 05:34

Set the backBarButtonItem on the previous view controller (the one that you will return to when you press the back button).

查看更多
狗以群分
4楼-- · 2019-06-09 05:44

Here's the answer. In the view controller:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"X";
    //Logout button
    UIBarButtonItem * logout = [[UIBarButtonItem alloc] initWithTitle:@"Logout" style: UIBarButtonItemStylePlain target:self action:@selector(goBack)];
    self.navigationItem.leftBarButtonItem = logout;
    [logout release];
}
查看更多
登录 后发表回答