How to create backBarButtomItem with custom view for a UINavigationController

前端 未结 14 1163
余生分开走
余生分开走 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

    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

提交回复
热议问题