How to assign my CustomNavigationBar to a UINaviga

2019-02-24 11:13发布

In order to customize the aspect of the navigationBar of my UINavigationController, I've been told to subclass the UINavigationBar class.

I need to change the height of the bar, placing an image instead of the title.. etc. I can't do it just using UINavigationBar properties.

Now, my issue is, how to assign to the UINavigationController, my CustomNavigationBar instance ? I can't use UINavigationController.navigationBar because it is read-only.

The only way seems to load a xib, but subclassing UINavigationController is not reccomended by Apple, so I'm a bit confused.

1条回答
闹够了就滚
2楼-- · 2019-02-24 11:45

Depending exactly on how custom you want the nav bar, the following may help you:

1) An image in the bar, replacing the title text. (self is a UIViewController)

UIImageView *titleImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image.png"]];
self.navigationItem.titleView = titleImg;
[titleImg release];

2) A totally custom nav bar

Subview UIView (CORRECTION: UINavigationController) with a nib, using (for example, of iPhone portrait orientation) a imageview as the background (could have a gradient) and then custom buttons on the left and right side, all hooked up to your relevant responder functions. As long as you add this nav bar view as a subview to each view controller etc each time a new one is pushed to the stack, you would have overriden Apple's standard nav bar. (remember to set theirs to hidden in the app delegate)


Edit:

NavigationBar.h

@interface NavigationBar: UIViewController
{   
    IBOutlet UIImageView* navigationBarImgView; // remember to set these 4 IBOutlets as properties with (nonatomic, retain) and synthesize them.

    IBOutlet UILabel* controllerHeader;

    IBOutlet UIButton* rightButton;
    IBOutlet UIButton* leftButton;

    eController controller;

    int screenWidth;
}

NavigationBar.m

-(id)initNavigationBar: (NSString*)name bundle:(NSBundle*)bundle: (eController)controllerName: (int)inScreenWidth
{
    [super initWithNibName:name bundle:bundle];

    controller = controllerName;
    screenWidth = isScreenWidth;

    return self;
}

You can see my init here only passes in a few things - an enum which was defined in my app delegate which contains the names of all possible view controllers. We interpret this enum in my custom Navigation Bar class and switch between all the possible controllers, and then setup their buttons and titles and the actions that get fired off using that information. The screen width is important - although you may not need this if you create the bar in IB, set the size of it to fill up the allocated space for both orientations.

Keep me posted :)

查看更多
登录 后发表回答