【问题标题】:How to avoid UIToolbar's tintColor to change UIButtonItem button color?如何避免 UIToolbar 的 tintColor 改变 UIButtonItem 按钮颜色?
【发布时间】:2013-12-16 09:39:32
【问题描述】:

在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];

我已经尝试创建一个UIToolBar 并通过Interface Builder 向其中添加一些项目。外观很好。 UIBarButtonItem 的图片颜色就是原始图片的颜色。

如果我想通过编写代码来设置UIToolBarUIBarButtonItem 的某些属性,我怀疑是否需要添加一些代码。你能告诉我怎么做吗?

【问题讨论】:

    标签: ios uibarbuttonitem uitoolbar


    【解决方案1】:

    虽然它不应该是必需的,但我从 iOS7 开始的彩色 UIBarButtonItem 已经完成了:

    对于目标 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 方法的链接。
    • 我一直在寻找很多东西来覆盖色调。效果很好,谢谢弗朗索瓦 :)
    【解决方案2】:

    您必须使用以下代码:

    _bottomBar.transculantColor = No;
    [_bottomBar setBackgroundColor:[UIColor clearColor]];
    

    【讨论】:

    • 那个代码没有生效。如何避免UIToolbar tintColor改变UIButtonItem按钮颜色?
    猜你喜欢
    • 2013-09-14
    • 2011-07-31
    • 1970-01-01
    • 2021-11-16
    • 2015-11-23
    • 1970-01-01
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多