How to create backBarButtomItem with custom view for a UINavigationController

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

    I too have been having problems with customView on a navigationItem.backBarButtonItem. I suspect it's probably just b0rked in the SDK.

    While the workarounds outlined here do work, I've come up with a solution which is a little more elegant: it still uses navigationItem.leftBarButtonItem, but takes care of it for you automagically (no more need for 'child' view controllers to need to know anything about their 'parent' and/or to manually set navigationItem.leftBarButtonItem).


    First up, have some class be a UINavigationControllerDelegate for the UINavigationController whose back button you're interested in. Then, in this class, set up something like the following willShowViewController delegate method:

    -(void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
        // reference to view controller stack
        NSArray *viewControllers = [ navigationController viewControllers ];
        if( [ viewControllers count ] > 1 ){
            // the view controller we'll be linking to
            UIViewController *backViewController = [ viewControllers objectAtIndex: [ viewControllers count ] - 2 ];
            // create custom UIBarButtonItem
            UIBarButtonItem *leftButton = [[ UIBarButtonItem alloc ] initWithCustomView: someCustomView ];
            // set it as the leftBarButtonItem on the incoming viewcontroller
            viewController.navigationItem.leftBarButtonItem = leftButton;
            // tidy up
            [ leftButton release ];
        }
    }
    

    I had some further problems with this; it seems that UIBarButtonItem.action and UIBarButtonItem.target don't work when it's a navigationItem.leftBarButtonItem. So, you're left with a custom back button that doesn't actually go back. I'll leave responding to touches in your custom view as an exercise for the reader (I used a UIButton), but you'll need add this method to your delegate class:

    -(void)onDummyBackButtonTapped{
        [ someNavigationController popViewControllerAnimated: YES ];
    }
    

    and hook it up to fire when your custom view is tapped.

提交回复
热议问题