2011-07-17 214 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]; 
}