2012-07-02 137 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

相關問題