0
votes

Simple question: in the main view controller of my app (which is in a navigation controller), I am customizing the nav bar with something like this:

self.navigationItem.titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"titleImage"]];

UIButton *menuButton = [[UIButton alloc] init];
[menuButton setImage:[UIImage imageNamed:@"menuIcon"] forState:UIControlStateNormal];
[menuButton setFrame:CGRectMake(0, 0, 34, 34)];

UIBarButtonItem *menuItem = [[UIBarButtonItem alloc] initWithCustomView:menuButton];
self.navigationItem.rightBarButtonItem = menuItem;

I want these elements - the title view and the right bar button - to remain consistent throughout the app as I push and pop new view controllers onto and off of my navigation controller.

Of course, I could just set my custom items up in viewDidLoad of every view controller that is pushed onto my navigation stack, but this means that during the animation between two view controllers, my custom items are animated in and out, which is not as clean as I would like.

Any suggestions on how I would go about maintaining those custom elements on my nav bar when switching from vc to vc? Thanks!

1

1 Answers

0
votes

You could create your own navigation item class that subclasses UIButton and set all the appearance in that class, then just set your navigation items as those custom UIButtons.

Something like this:

In CustomButton.h

#import <UIKit/UIKit.h>

@interface CustomButton : UIButton

@end

Then in CustomButton.m

@implementation CustomButton

- (id)initWithFrame:(CGRect)frame
 {
     self = [super initWithFrame:frame];
     if (self) {
            //Set images etc.
            [menuButton setImage:[UIImage imageNamed:@"menuIcon"] forState:UIControlStateNormal];
            [menuButton setFrame:CGRectMake(0, 0, 34, 34)];
        }
        return self;
    }


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end

Then in your viewController:

#import CustomButton.h

- (void)viewDidLoad
{
     CustomButton *button = [[CustomButton alloc]init];
     self.navigationItem.leftBarButton = [[UIBarButtonItem alloc] initWithCustomView:button];
}