How can I show a custom image in navigation bar back button instead of default buttons which are shown by nav bar itself

前端 未结 3 1889
陌清茗
陌清茗 2021-02-14 22:04

On navigating to any view in an app which has navigation controller implemented, it shows a back button to go to the previous view. Is there a way I can use custom image instead

3条回答
  •  攒了一身酷
    2021-02-14 22:21

    Yes you can.

    You can control how the standard back button will look when another view controller is pushed on top of a given view controller by setting its navigation item's back bar button item (you can customize the title or use an image):

    UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:nil action:nil];
    self.navigationItem.backBarButtonItem = btn;
    [btn release];
    
    UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithImage:yourImage style:UIBarButtonItemStyleBordered target:nil action:nil];
    self.navigationItem.backBarButtonItem = btn;
    [btn release];
    

    Note: you configure this in a "parent" view controller that may have other view controller(s) pushed on top of it. The configuration is done in the "parent" and the appearance of the back button is changed when some view controller is on top. Tapping the back button brings you back as expected.


    You can also create your own UIBarButtonItem and set it as the leftButtonItem on the navigation bar on the current view controller:

    UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithImage:yourImage style:UIBarButtonItemStyleBordered target:self action:@selector(yourMethod:)];
    self.navigationItem.leftBarButtonItem = btn;
    [btn release];
    

    Note: in this case, the back / left bar button item is changed for the current view controller (when it is on top). You must implement the yourMethod: method. If you simply want the button to go back, you have to handle popping the view controller yourself by calling [self.navigationController popViewControllerAnimated:YES];.

提交回复
热议问题