How to create backBarButtomItem with custom view for a UINavigationController

前端 未结 14 934
余生分开走
余生分开走 2020-11-29 19:39

I have a UINavigationController into which I push several views. Inside viewDidLoad for one of these views I want to set the self.navigationI

相关标签:
14条回答
  • 2020-11-29 20:15

    backBarButtonItem is not a read-only property. I'm not sure why it behaves so strangely, and the above is a valid (if less-than-ideal) workaround.

    It behaves strangely because setting a vc's backBarButtonItem doesn't change anything about the appearance of the vc's navigation item - instead, it changes the button that points BACK to the vc. See updating the navigation bar from Apple FMI.

    That said I haven't had a whole lot of luck getting it to work myself. If you look around this site, you'll find some threads that suggest placing code very similar to what you already have immediately before the call to push a new view on the stack. I've had some luck there, but unfortunately not when it comes to using a custom image.

    0 讨论(0)
  • 2020-11-29 20:15

    This is how I create a custom square back button with an arrow instead of the usual text.

    I simply setup a delegate for my UINavigationController. I use the app delegate for that because the window root view controller is the UINavigationController i want to control.

    So AppDelegate.m (ARC):

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        ((UINavigationController*)_window.rootViewController).delegate = self;
        return YES;
    }
    
    #pragma mark - UINavigationControllerDelegate
    
    - (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
        if(navigationController.viewControllers.count > 1) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button setImage:[UIImage imageNamed:@"back-arrow.png"] forState:UIControlStateNormal];
            [button setBackgroundColor:[UIColor grayColor]];
            button.frame = CGRectMake(0, 0, 44, 44);
            viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
            [button addEventHandler:^(id sender) {
                [navigationController popViewControllerAnimated:YES];
            } forControlEvents:UIControlEventTouchUpInside];
        }
    }
    

    I'm using BlocksKit to catch the button tap event. It's very convenient for stuff like this but you can also use the regular addTarget:action:forControlEvents: method

    0 讨论(0)
提交回复
热议问题