0

我正在经历创建自定义 UINavigationBar 的不同选项,并且由于我的应用程序是 iOS 5+,我正在使用以下代码:

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

现在我想在最右边有一个自定义图像按钮,有点迷失了。我应该采用另一种方式,将 UINavigationBar 子类化并添加一个按钮,还是有更简单的方法?

4

1 回答 1

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
于 2012-07-02T04:09:44.537 回答