如何避免UIToolbar的tintColor改变UIBarButtonItem按钮颜色?

4
在iOS7中,我创建了一个UIBarButtonItem,并使用绿色的图片进行初始化。但是最终这个UIBarButtonItem的图片外观是相同形状但颜色不同的图片。颜色被改变成了蓝色。
以下是代码:
_recordVoiceItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"voiceIcon"] style:UIBarButtonItemStylePlain target:self action:nil];

    _textView = [[UITextView alloc] initWithFrame:CGRectMake(40, 4, 220, BOTTOM_BAR_HEIGHT - 2*4)];
    _textView.layer.borderWidth = 1.f;

    _rightItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"modeIcon"] style:UIBarButtonItemStylePlain target:self action:nil];

    _bottomBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, self.view.frame.origin.y + self.view.frame.size.height - BOTTOM_BAR_HEIGHT, self.view.frame.size.width, BOTTOM_BAR_HEIGHT)];

    _bottomBar.items = @[_recordVoiceItem,[[UIBarButtonItem alloc] initWithCustomView:_textView],_rightItem];

    [self.view addSubview:_bottomBar];

我尝试通过Interface Builder创建UIToolBar并添加一些项目,外观很好。但是UIBarButtonItem图像的颜色是原始图像的颜色。

我怀疑如果我想通过编写代码来完成这个操作,我需要添加一些代码来设置UIToolBarUIBarButtonItem的某些属性。你能告诉我如何做吗?

2个回答

17
尽管没有必要,但自从iOS7以来,我的有颜色的UIBarButtonItem是这样完成的:
对于Objective C:
UIImage* itemImage= [UIImage imageNamed:@"menu.png"]; // Colored Image
itemImage         = [itemImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
_itemButton       = [[UIBarButtonItem alloc] initWithImage:itemImage style:UIBarButtonItemStyleBordered target:self action:@selector(itemSelected:event:)];

UIImageRenderingModeAlwaysOriginal 在这里是关键。

对于 Swift 3

    // Use the colored image menu.png as a UIBarButtonItem
    if var itemImage   = UIImage(named: "menu") {
        itemImage      = itemImage.withRenderingMode(.alwaysOriginal)
        let itemButton = UIBarButtonItem(image: itemImage, style: .plain, target: self, action: #selector(self.itemSelected(_:)))

        self.navigationItem.rightBarButtonItem  = itemButton
    }

再次强调,withRenderingMode(.alwaysOriginal) 是关键。


这个 tintColorUIImage 中的新 API 是我见过的最糟糕的 API 设计失败。在 tintColor 的文档中,苹果应该添加一个链接到这个 UIImage 方法。 - Marek R
我一直在寻找覆盖色调的方法。非常感谢Francois :) - Shashi3456643

0
你需要使用以下代码:
_bottomBar.transculantColor = No;
[_bottomBar setBackgroundColor:[UIColor clearColor]];

那段代码没有生效。如何避免 UIToolbar tintColor 改变 UIButtonItem 按钮颜色? - user2416374

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接