Reputation: 6205
Im going through the different options of creating a custom UINavigationBar and since my app is iOS 5+, i am using this code:
// Set the background image all UINavigationBars
[[UINavigationBar appearance] setBackgroundImage:NavigationPortraitBackground
forBarMetrics:UIBarMetricsDefault];
Now i want a custom image button on the very right side and am a bit lost. Should I go another way, subclass UINavigationBar and add a button to it or would there be an easier way?
Upvotes: 0
Views: 591
Reputation: 43330
Absolutely subclass this thing. UINavigationBar is easy to subclass, but very hard to put into a navigation controller. I will show you my subclass (CFColoredNavigationBar), which also comes with an arbitrarily colored background for free.
//.h
#import <UIKit/UIKit.h>
@interface CFColoredNavigationBar : UINavigationBar
@property (nonatomic, strong) UIColor *barBackgroundColor;
@property (nonatomic, strong) UIButton *postButton;
@end
//.m
#import "CFColoredNavigationBar.h"
@implementation CFColoredNavigationBar
@synthesize barBackgroundColor = barBackgroundColor_;
@synthesize postButton = postButton_;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
-(void)awakeFromNib {
postButton_ = [[UIButton alloc]initWithFrame:CGRectMake(CGRectGetWidth(self.frame)-60, 0, 60.0f, CGRectGetHeight(self.frame))];
[postButton_ setImage:[UIImage imageNamed:@"Post.png"] forState:UIControlStateNormal];
[self addSubview:postButton_];
}
- (void)drawRect:(CGRect)rect {
if (barBackgroundColor_ == nil) {
barBackgroundColor_ = [UIColor blackColor];
}
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [barBackgroundColor_ CGColor]);
CGContextFillRect(context, CGRectInset(self.frame, 0, self.frame.size.height*-2));
}
@end
Upvotes: 1