How to create backBarButtomItem with custom view for a UINavigationController

前端 未结 14 1215
余生分开走
余生分开走 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 19:56

    I never been able to create a proper UIBarButtonItem with custom view and setBackBarButtonItem.

    Here's the solution i found : let net UINavigationControllerDelegate handles everything! The trick here is to call the popViewControllerAnimated: method of the viewController.navigationController so you don't have to create any custom method.

    - (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
        if([navigationController.viewControllers count ] > 1) {
            UIView *backButtonView = [[UIView alloc] initWithFrame:CGRectMake(0,0,70,35)];
            UIButton *myBackButton = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
            [myBackButton setFrame:CGRectMake(0,0,70,35)];
            [myBackButton setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
            [myBackButton setEnabled:YES];
            [myBackButton addTarget:viewController.navigationController action:@selector(popViewControllerAnimated:) forControlEvents:UIControlEventTouchUpInside];
            [backButtonView addSubview:myBackButton];
            [myBackButton release];
            UIBarButtonItem* backButton = [[UIBarButtonItem alloc] initWithCustomView:backButtonView];
            viewController.navigationItem.leftBarButtonItem = backButton;
            [backButtonView release];
            [backButton release];
        }
    }
    

提交回复
热议问题