iphone - 更改 UINavigationBar 中的 UIButton 高亮图像

标签 iphone objective-c ios uinavigationcontroller uinavigationbar

我试图在突出显示时更改 UIButton 中的 UIImageUIButton 位于 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/

相关文章:

ios - 检测触摸并按住屏幕 iPhone (Xcode)

iphone - 如何控制 UIWebView 的颜色(内容加载前)?

ios - 用户在 iOS 上关闭应用程序后执行操作

iphone - 如何调整 UITableViewCell 的大小以使其适合任何详细信息文本标签

ios - 在 iOS 的 UITextView 中检测属性文本的点击

iphone - JSON如何调用不同列表中的对象

ios - 类似 prepareForSegue 的东西,但用于返回时

ios - 链接器命令失败,退出代码为 1(使用 -v 查看)

iphone - 如何在 Objective C 中将好友标记为 Facebook 中的用户帖子

ios:uitableview 部分标题 anchor 到表顶部