2012-03-02 61 views
1

我有一個UIButton與圖像的自定義視圖的UIBarButtonItem,我希望有不同的取向不同的UIImage,所以這裏是我的代碼:改變的UIBarButtonItem的UIButton的形象

UIButton * backButton = (UIButton *) ((UIBarButtonItem *) self.navBar_.topItem.leftBarButtonItem).customView; 
     if (UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation]) && IS_IPAD) {   
      [backButton setBackgroundImage:[UIImage imageNamed:@"back-landscape.png"] forState:UIControlStateNormal]; 
      [backButton setFrame: CGRectMake(0, 0, 46, 35)]; 
     } else { 
      [backButton setBackgroundImage:[UIImage imageNamed:@"back-reading.png"] forState:UIControlStateNormal]; 
      [backButton setFrame: CGRectMake(0, 0, 23, 19)]; 
     } 

儘管如此,這並不改變UIButton圖像,這是爲什麼?

回答

3

試試這個: -

UIButton * backButton ; 
if (UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation]) && IS_IPAD) 
{ 
    backButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 66.0f, 36.0f)];  
    [backButton setImage:[UIImage imageNamed:@"back-landscape.png"] forState:UIControlStateNormal]; 

} 
else 
{ 
    backButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 23, 19)];  
    [backButton setImage:[UIImage imageNamed:@"back-reading.png"] forState:UIControlStateNormal]; 
    [backButton setFrame: CGRectMake(0, 0, 23, 19)]; 
} 

[backButton addTarget:self action:@selector(goToHome) forControlEvents:UIControlEventTouchUpInside]; 
UIBarButtonItem *HomeButton = [[UIBarButtonItem alloc] initWithCustomView: backButton]; 
[self.navigationItem setLeftBarButtonItem:HomeButton]; 
+0

是啊這工作..但我不得不再次分配一個新的UIButton – adit 2012-03-02 18:01:54

+0

這不會改變UIBarButton它只是創建一個新的 – 2014-06-27 05:50:17

0

您可以使用新的代理類+ + appereance方法檢查DOC,但僅適用於iOS5。對於較早的支持,您可以在視圖旋轉視圖控制器方法-willRotateToInterfaceOrientation時更新圖像。 僑

+0

viewWillRotate就是上面的方法是。但它不起作用 – adit 2012-03-02 06:12:53

+0

嘗試調用[self.view setNeedsDisplay];在方法結束時。你打電話超級在-viewWillRotate – Andrea 2012-03-02 07:46:17

1

你應該通知你說它是一個UIBarButtonItem,但你在代碼中使用UIButton

從ios5.0,您可以用UIAppearence Protocol改變UIBarButtonItem背景圖片,如:


[[UIBarButtonItem appearance] setBackgroundImage: forState: barMetrics:] 

您還可以使用elppa的方法,但是請注意,你可以直接使用UIImageViewcustomView參數。

0

使用自定義的UIButton創建UIBarButton:

_optionsButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
[_optionsButton setImage:[UIImage imageNamed:@"menu2.png"] forState:UIControlStateNormal]; 
[_optionsButton addTarget:self action:@selector(optionsButtonPressed) forControlEvents:UIControlEventTouchUpInside]; 

UIBarButtonItem * optionsItem = [[UIBarButtonItem alloc] initWithCustomView:_optionsButton]; 

然後設置背景圖片,你會(而不是試圖改變爲UIBarButton圖像)通常爲的UIButton。

[_optionsButton setImage:[UIImage imageNamed:@"keyboard.png"] forState:UIControlStateNormal]; 

這對我

注偉大的工作:當我正經歷這個,我正在改變根據當前的照片是什麼照片。我發現我不得不使用:

if ([[_optionsButton imageForState:UIControlStateNormal] isEqual:[UIImage imageNamed: @"keyboard.png"]]) { 
    // Code for the certain button function 
} 

來得到它的工作