改变的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];
答
你应该通知你说它是一个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];
然后设置背景图片,你会(而不是试图改变为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
}
来得到它的工作
是啊这工作..但我不得不再次分配一个新的UIButton – adit 2012-03-02 18:01:54
这不会改变UIBarButton它只是创建一个新的 – 2014-06-27 05:50:17