2012-10-29 166 views

回答

19

希望這有助於

viewController.navigationItem.titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"yourimage.png"]]; 
UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithCustomView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"yourimage2.jpg"]]];  
viewController.navigationItem.rightBarButtonItem = item;  
+0

我想這就是我要找的。我該如何處理這個按鈕的觸摸? –

+1

不錯!我試過這個和下面的Kamarshad答案,但這個答案好多了,因爲按鈕圖標看起來不錯,「initWithCustomView」 – swiftBoy

1
UIView *viewWithButtons = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 44)]; 
//view customization 
UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
//Button customiztaion 
[viewWithButtons addSubview:leftButton]; 
UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
//Button customiztaion 
[viewWithButtons addSubview:rightButton]; 
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:viewWithButtons]; 
[viewWithButtons release]; 
8

這裏的代碼,只需撥打下面的方法從viewDidLoad方法

- (void)addCustomButtonOnNavBar 
    { 
    UIBarButtonItem * item1= [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"passImageNmae1"] style:UIBarButtonItemStylePlain target:self action:@selector(yourButtonAction1)]; 
    UIBarButtonItem * item2= [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"passImageNmae2"] style:UIBarButtonItemStylePlain target:self action:@selector(yourButtonAction2)]; 
    NSArray * buttonArray =[NSArray arrayWithObjects:item1,item2 ,nil]; 

    self.navigationItem.rightBarButtonItems =buttonArray; 

    } 
+1

這是行不通的。它試圖把圖像放在一個按鈕上。我希望圖像本身就是按鈕。 –

+0

換句話說,我無法實現使用此代碼發佈的屏幕截圖。 –

+0

@Karamshad Button非常大。如何設置適合導航欄的正確大小? –

1

我用一個類別是:

的UIBarButtonItem + WithImageOnly。 h:

#import <UIKit/UIKit.h> 

@interface UIBarButtonItem (WithImageOnly) 

- (id)initWithImageOnly:(UIImage*)image target:(id)target action:(SEL)action; 

@end 

的UIBarButtonItem + WithImageOnly.m:

#import "UIBarButtonItem+WithImageOnly.h" 

@implementation UIBarButtonItem (WithImageOnly) 

- (id)initWithImageOnly:(UIImage *)image target:(id)target action:(SEL)action {  
    CGRect frame = CGRectMake(0, 0, image.size.width, image.size.height); 
    frame = CGRectInset(frame, -5, 0); 

    UIButton *button = [[UIButton alloc] initWithFrame:frame]; 
    [button setImage:image forState:UIControlStateNormal]; 
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside]; 

    return [self initWithCustomView:button]; 
} 

@end 

用法:

UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithImageOnly:[UIImage imageNamed:@"image"] target:self action:@selector(someAction:)]