2011-07-17 161 views
4

我创建了一个自定义按钮并将其应用于UIbarbuttonitem。 没有错误,但没有显示在导航栏:( 上这是我的代码 -如何将图像添加到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]; 

如果谁可以解决我的代码?:)

回答

9

the docs:

initWithImage:style:target:action: 

试试看。

+0

这样? UIBarButtonItem \t * button = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStyleBordered target:self action:@selector(goBack :)]; Stil不工作..没有错误,但没有显示:( – Leanne

+1

请确保您的图像不返回为零 – DexterW

+0

啊nvm,它工作:) thanx堆! – Leanne

1

要使用正确的色彩设置任何图像,使用的UIButton,设置 “为国家形象”,然后创建的UIBarButtonItemcustomView

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]; 
1

一个最简单的方法是:

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]; 
}