Reputation: 1028
I have a problem to which I can't found a solution right now. In my application I have multiple buttons in my NavigationBar which are required throughout the app, rather than creating the buttons in every view controller I want to make a sub class of UINavigationBar or UINavigationController(i don't know which one). So that whenever the user moves between the views the navigation bar always contains those buttons. I have searched very much till now regarding this but couldn't found anything worth. Please suggest me a way to do so, thanks in advance.
Upvotes: 0
Views: 145
Reputation: 3399
You can subClass standard UINavigationBar
to achieve this
@interface CustomNavigationBar : UINavigationBar
- (id)initWithFrame:(CGRect)frame;
@end
@implementation CustomNavigationBar
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
UIButton *btn=[UIButton buttonWithType:UIButtonTypeContactAdd];
[btn addTarget:self action:@selector(<#selector#>) forControlEvents:<#(UIControlEvents)#>]
[self addSubview:btn];
...
...
}
return self;
}
- (void)drawRect:(CGRect)rect {
[[UIColor redColor] setFill];
UIRectFill(rect);
}
@end
To use this is StoryBoard
or xib
, simply change standard class name to CustomNavigationBar
.
OR
If you want it programmatically
In AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen] bounds]];
UINavigationController *navVC = [[UINavigationController alloc] initWithNavigationBarClass:[CustomNavigationBar class] toolbarClass:nil];
UIStoryboard *mStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
ViewController *VC1 = [mStoryboard instantiateViewControllerWithIdentifier:@"VC"];
[navVC setViewControllers:[NSArray arrayWithObject:VC1] animated:NO];
[self. window setRootViewController:navVC];
[self. window makeKeyAndVisible];
return YES;
}
Upvotes: 0
Reputation: 3908
#import "CustomNavBar.h"
@implementation CustomNavBar
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.tintColor=[UIColor greenColor];
}
return self;
}
- (void)drawRect:(CGRect)rect {
UIImage *image = [UIImage imageNamed:@"Custom-Nav-Bar-BG.png"];
[image drawInRect:CGRectMake(0, 0, 40, self.frame.size.height)];
UIButton *btn=[UIButton buttonWithType:UIButtonTypeContactAdd];
[btn drawRect:CGRectMake(42, 0, 40, self.frame.size.height )];
UIButton *btn2=[UIButton buttonWithType:UIButtonTypeContactAdd];
[btn2 drawRect:CGRectMake(82, 0, 40, self.frame.size.height )];
}
@end
Upvotes: 0