2012-07-02 63 views
0

林经历,因为我的应用程序是iOS的创建自定义UINavigationBar的和不同的选择5+,我使用此代码:如何自定义按钮添加到UINavigationBar的(一拉四方)

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

现在我想要一个自定义图像按钮在右侧,有点迷路。我应该以另一种方式,UINavigationBar的子类,并添加一个按钮,或者会有一个更简单的方法?

+0

你在使用故事板吗? –

+0

不,我设法设置一个rightBarButtonItem,但我不能设置定位,所以我没有太多的运气 – jfisk

回答

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 
+0

最好的部分,这个东西是操作系统版本不可知论的。应该一路回到2.0 – CodaFi

+0

现在我有我的自定义导航栏设置从一个笔尖,所以initWithFrame不会被调用。我怎么能在这方面做到这一点?或者,如果你可以分享你在导航控制器中实现自定义导航栏的方式,那也会很棒:) – jfisk

+0

使用我在initWithNibName中提供的代码:并将它移入到awakeFromNib中。简单!我的方法也是基于xib的。我会编辑这个。 – CodaFi

相关问题