我有一个带有图像的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图像,为什么会这样?
答案 0 :(得分: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];
答案 1 :(得分:1)
您应该通知您说它是 UIBarButtonItem
,但您在代码中使用 UIButton
。
从ios5.0开始,您可以使用UIAppearence Protocol
更改 UIBarButtonItem
背景图片,例如:
[[UIBarButtonItem appearance] setBackgroundImage: forState: barMetrics:]
您也可以使用elppa的方法,但请注意,您可以直接使用UIImageView
作为customView
参数。
答案 2 :(得分:0)
您可以使用带有+ appereance方法的新代理类检查DOC,但仅适用于iOS5。对于早期支持,您可以在视图旋转视图控制器方法-willRotateToInterfaceOrientation时更新图像。 侨
答案 3 :(得分: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];
然后像往常一样为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
}
让它发挥作用