改变的UIBarButtonItem的UIButton的形象

问题描述:

我有一个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图像,这是为什么?

试试这个: -

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

您可以使用新的代理类+ + 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

你应该通知你说它是一个UIBarButtonItem,但你在代码中使用UIButton

从ios5.0,您可以用UIAppearence Protocol改变UIBarButtonItem背景图片,如:


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

您还可以使用elppa的方法,但是请注意,你可以直接使用UIImageViewcustomView参数。

使用自定义的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 
} 

来得到它的工作