我试图在突出显示时更改 UIButton
中的 UIImage
。 UIButton
位于 UINavigationController
中。
我有以下代码:
UIView *containingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 28, 28)];
UIButton *barUIButton = [UIButton buttonWithType:UIButtonTypeCustom];
[barUIButton setImage:[UIImage imageNamed:@"Add.png"] forState:UIControlStateNormal];
barUIButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
barUIButton.frame = CGRectMake(-9, 0, 28, 28);
[barUIButton addTarget:self action:@selector(addButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[barUIButton setImage:[UIImage imageNamed:@"AddHighlighted.png"] forState:UIControlStateSelected | UIControlStateHighlighted];
[containingView addSubview:barUIButton];
UIBarButtonItem *containingBarButton = [[[UIBarButtonItem alloc] initWithCustomView:containingView] autorelease];
self.navigationItem.rightBarButtonItem = containingBarButton;
突出显示时不会显示新图像,现有图像周围只有黑色阴影。
这是为什么?
最佳答案
UIButton
实例似乎没有在触摸事件中突出显示或被选中。这可能是因为 UIBarButtonItem
实例不像普通按钮那样工作;事实上,它们甚至不是 UIButton 子类
。
有一个解决方法。如果您在实例变量中保留对 UIButton
的引用,则可以添加代码来更改按钮的图像:
[barUIButton addTarget:self action:@selector(pressDown:) forControlEvents:UIControlEventTouchDown];
[barUIButton addTarget:self action:@selector(pressUp:) forControlEvents:UIControlEventTouchUp];
在pressDown:
和pressUp:
中,你可以设置
-(void)pressDown:(id)sender
{
[barUIButton setImage:[UIImage imageNamed:@"Add.png"] forState:UIControlStateNormal];
}
pressUp:
也类似。
关于iphone - 更改 UINavigationBar 中的 UIButton 高亮图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9572776/