繁体   English   中英

更改UIBarButtonItem UIButton的图像

[英]changing UIBarButtonItem UIButton's image

我有一个带有图像的UI按钮的自定义视图的UIBarButtonItem,我想为不同的方向设置不同的UIImage,所以这是我的代码:

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

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

从ios5.0开始,您可以使用UIAppearence Protocol来更改UIBarButtonItem背景图像,如:


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

您也可以使用elppa的方法,但请注意您可以直接使用UIImageView作为customView参数。

使用自定义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];

然后像往常一样为UIButton设置背景图像(而不是尝试更改UIBarButton的图像)。

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

这对我很有用

注意:当我经历这个时,我正在改变图片,具体取决于当前的图片。 我发现我必须使用:

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

让它工作

您可以使用带有+ appereance方法的新代理类检查DOC,但仅适用于iOS5。 对于早期支持,您可以在视图旋转视图控制器方法-willRotateToInterfaceOrientation时更新图像。 再见

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM