如何将自定义按钮添加到UINavigationBar(la Foursquare)

时间:2012-07-02 03:13:03

标签: ios ios5 uinavigationcontroller uinavigationbar

我正在浏览创建自定义UINavigationBar的不同选项,因为我的应用程序是iOS 5+,我正在使用此代码:

// Set the background image all UINavigationBars
[[UINavigationBar appearance]  setBackgroundImage:NavigationPortraitBackground 
                                    forBarMetrics:UIBarMetricsDefault];

现在我想要一个非常右侧的自定义图像按钮,我有点迷失了。我应该采用另一种方式,继承UINavigationBar并为其添加一个按钮,还是会有更简单的方法?

1 个答案:

答案 0 :(得分:1)

绝对是这个东西的子类。 UINavigationBar很容易子类化,但很难放入导航控制器。我将向您展示我的子类(CFColoredNavigationBar),它还免费提供任意彩色背景。

//.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