简体   繁体   中英

How to add a custom button to a UINavigationBar (a la Foursquare)

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM