我已经永远拥有了这个代码,它曾经工作过,但它开始在iOS 6中表现出令人讨厌的行为。在SO上有几个类似的线程,但是我还没有找到解决方案我很舒服。我找到了解决办法(见下文),但这似乎不是“正确”的做法。
Here's a thread with the same issue, but no answers.
当我将图片用作UIBarButtonItem
并将其放入UIToolbar
时,UIToolbar
的包含矩形并非完全透明。我用于UIBarButtonItem
的PNG图像是透明的,所以这不是问题。这是一个例子:
当我使用文本而不是图像作为UIBarButtonItem
时,透明度按预期工作。如此:
以下是永远有效的代码:
NSMutableArray *buttonItems = [[[NSMutableArray alloc] initWithCapacity: 1] autorelease];
UIImage *printButtonImage = [UIImage imageNamed:@"buttonPrint.png"];
UIToolbar *toolBarButtons = [[[UIToolbar alloc] initWithFrame:CGRectMake( 0, 0, 52.0, 44.01 )] autorelease];
UIBarButtonItem *printButton = [[[UIBarButtonItem alloc] initWithImage:printButtonImage style:UIBarButtonItemStyleBordered target:self action:@selector(printDocument:)] autorelease];
[buttonItems addObject:printButton];
[toolBarButtons setItems:buttonItems animated:YES];
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:toolBarButtons] autorelease];
根据SO的建议,我在[toolBarButtons setItems...]
之前添加了此内容,但它没有任何影响:
toolBarButtons.backgroundColor = [UIColor clearColor];
[toolBarButtons setTranslucent:YES];
[toolBarButtons setOpaque:NO];
I found this thread,jd的回答提供了解决方法(编辑以匹配我的变量):
const float colorMask[6] = {222, 255, 222, 255, 222, 255};
UIImage *img = [[UIImage alloc] init];
UIImage *maskedImage = [UIImage imageWithCGImage: CGImageCreateWithMaskingColors(img.CGImage, colorMask)];
[toolBarButtons setBackgroundImage:maskedImage forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
我还看到了这个问题的几个解决方案,需要获取navigationController
的顶部或底部的颜色并应用渐变,但我拒绝相信没有办法制作矩形UIToolbar
完全透明,应该允许navigationController
颜色通过,渐变和所有。
应用掩码图片 真的 是模拟正确UI体验的唯一方法吗? Apple 真的 没有提供简单地让UIToolbar
包含矩形完全透明的方法吗?
目前,我有正确的行为,但我觉得我没有正确的解决方案。这感觉就像一个黑客。有没有人知道有更好的方法来实现这个目标?
答案 0 :(得分:3)
我在我的应用中做同样的事情。 (这让我很震惊,我们必须在UIToolbar
中托管UINavigationBar
只是因为UINavigationBar
不会像UIBarButtonItem's
一样呈现UIToolbar
。)
以下是我为避免您遇到的问题而采取的措施:
toolbar.barStyle = self.navigationController.navigationBar.barStyle;
toolbar.tintColor = self.navigationController.navigationBar.tintColor;
我最后一次检查时,navigationBar.barStyle是一个UIBarStyle枚举中未记录的值......我认为它是'3'。
编辑:令人讨厌的是,这不适用于iPhone,因为它适用于iPad ......
这个UIToolbar子类似乎工作正常。使用它代替普通的UIToolbar:
@interface NavToolbar : UIToolbar
@end
@implementation NavToolbar
- (void) layoutSubviews
{
[super layoutSubviews];
self.backgroundColor = [UIColor clearColor];
self.opaque = NO;
}
- (void) drawRect:(CGRect)rect
{
}
@end
并且,这是用于演示使用它的代码。没有NavToolbar,我会看到你提出的问题;使用NavToolbar可以根据需要使用它。在iOS6手机模拟器中测试过。
- (void)viewDidLoad
{
[super viewDidLoad];
UIToolbar* tb = [[NavToolbar alloc] initWithFrame: CGRectMake(0, 0, 44, 44)];
UIBarButtonItem* bbi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target: nil action: nil];
tb.items = @[bbi];
tb.barStyle = self.navigationController.navigationBar.barStyle;
UIBarButtonItem* tbbbi = [[UIBarButtonItem alloc] initWithCustomView: tb];
tbbbi.width = 44;
self.navigationItem.rightBarButtonItem = tbbbi;
}