如何将图片添加到UIBarButtonItem?

4

我创建了一个自定义按钮并将其应用于UIbarbuttonitem。没有错误,但导航栏上什么也没有显示:(

这是我的代码-

    //create a custom button
    UIImage *image = [UIImage imageNamed:@"TESTButton.png"];
    UIButton *myCustomButton = [UIButton buttonWithType:UIButtonTypeCustom];
    myCustomButton.bounds = CGRectMake( 0, 0, image.size.width, image.size.height );    
    [myCustomButton setImage:image forState:UIControlStateNormal];
    [myCustomButton addTarget:nil action:@selector(goBack:) forControlEvents:UIControlEventTouchUpInside];


    UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithCustomView:myCustomButton];
    self.navigationItem.leftBarButtonItem = button;
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;

    [button release];
    [myCustomButton release];
    [image release];
    [navID release];

有谁能修复我的代码吗?:)

3个回答

9

文档中得知:

initWithImage:style:target:action:

试一试。


像这样吗? UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStyleBordered target:self action:@selector(goBack:)]; 仍然不起作用...没有错误,但是什么也没有显示 :( - Leanne
1
确保您的图像不会返回为 nil。 - Dexter

3
要设置任何带有正确颜色的图像,请使用UIButton,设置“状态图像”,然后创建一个自定义视图的UIBarButtonItem。
UIImage *btnImage = [UIImage imageNamed:@"button"];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.bounds = CGRectMake( 0, 0, btnImage.size.width, btnImage.size.height );
[btn addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchDown];
[btn setImage:btnImage forState:UIControlStateNormal];
_buttonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];

2

最简单的方法之一是:

UIBarButtonItem *button2 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"backk.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backBtn:)];
self.navigationItem.leftBarButtonItem = button2;

操作方法:

- (IBAction)backBtn:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接