Custom back button in UINavigationController

前端 未结 10 1827
伪装坚强ぢ
伪装坚强ぢ 2020-12-28 16:59

For an application I\'m developing, I need to display a custom back button in a navigation bar. I have the button asset as a PNG image, and I\'m writing this code:



        
10条回答
  •  天命终不由人
    2020-12-28 17:34

    I do not think that ViewController itself should know anything about its back button According to OOP this is the responsibility of containerViewController in which your view controller is inserted, for example UINavigationController.

    Subclass your NavigationController and overload in it superClass method like this:

    @implementation STONavigationController
    
    - (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
    {
        [super pushViewController:viewController animated:animated];
        if ([self.viewControllers indexOfObject:viewController] != NSNotFound &&
            [self.viewControllers indexOfObject:viewController] > 0){
            UIImage *img = [UIImage imageNamed:@"back-1"];
            UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, img.size.width * 2, img.size.height * 2)];
            [backButton setBackgroundImage:img forState:UIControlStateNormal];
            UIBarButtonItem *barBackButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
            [backButton addTarget:self action:@selector(popCurrentViewController) forControlEvents:UIControlEventTouchUpInside];
            viewController.navigationItem.leftBarButtonItem = barBackButtonItem;
            viewController.navigationItem.hidesBackButton   = YES;
        }
    }
    
    - (void)popCurrentViewController
    {
        [self popViewControllerAnimated:YES];
    }
    
    @end 
    

提交回复
热议问题