iOS自定义右侧导航栏

时间:2013-12-24 09:27:48

标签: ios objective-c uinavigationbar

我正在尝试在导航控制器中为右侧条形项设置图像,但iOS 6会一直显示黑光。我已尝试过堆栈溢出的许多解决方案但无法使其工作。我目前的代码是:

UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"gear"]
                                                              style:UIBarButtonItemStylePlain
                                                             target:self
                                                             action:@selector(someMethod)];
[rightItem setImageInsets:UIEdgeInsetsMake(5, 5, 5, 5)];

[[self navigationItem] setRightBarButtonItem:rightItem];

在iOS7中看起来像这是我想要的: What I want 这就是iOS6 What I currently have

中的外观

4 个答案:

答案 0 :(得分:10)

试试这个:

UIImage *faceImage = [UIImage imageNamed:@"gear.png"];
UIButton *face = [UIButton buttonWithType:UIButtonTypeCustom];
face.bounds = CGRectMake( 10, 0, faceImage.size.width, faceImage.size.height );//set bound as per you want
[face addTarget:self action:@selector(someMethod) forControlEvents:UIControlEventTouchUpInside];
[face setImage:faceImage forState:UIControlStateNormal];
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithCustomView:face];
self.navigationItem.rightBarButtonItem = backButton;

它可以帮到你。

答案 1 :(得分:0)

首先使用图像创建UIButton,然后执行:

[[UIBarbuttonItem alloc] initWithCustomView:button];

答案 2 :(得分:0)

使用自定义视图:

UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeInfoLight]; // change this to use your image
[rightButton addTarget:self
                    action:@selector(yourAction:)
          forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
self.navigationItem.rightBarButtonItem = rightButtonItem;

答案 3 :(得分:0)

试试这个:

UIImage* image = [UIImage imageNamed:@"sample_Image.png"];

CGRect frameimg = CGRectMake(0, 0, image.size.width, image.size.height);
UIButton *someButton = [[UIButton alloc] initWithFrame:frameimg];
[someButton setBackgroundImage:image forState:UIControlStateNormal];
[someButton addTarget:self action:@selector(MethodName:)
     forControlEvents:UIControlEventTouchUpInside];   

UIBarButtonItem *barBtn =[[UIBarButtonItem alloc] initWithCustomView:someButton];

    [self.navigationItem setRightBarButtonItem:barBtn];