10

我想在 NavigationBar 的右侧创建一个带有图像作为按钮的 NavigationBar。

像下面的快照

在此处输入图像描述

我怎样才能做到这一点?

4

4 回答 4

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;    
于 2012-10-29T13:49:59.130 回答
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;

  }
于 2012-10-29T13:56:08.613 回答
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];
于 2012-10-29T13:49:00.973 回答
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:)]
于 2013-02-01T05:31:11.230 回答