Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid UIToolbar's tintColor to change UIButtonItem button color?

In iOS7,I Created a UIBarButtonItem and init with a image which color is green.But the final appearance of that UIBarButtonItem's image is a image with the same shape but different color.The color was changed to blue.

The code is below:

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

And I have tried to create a UIToolBar and add some items to it through Interface Builder.The appearance is fine. The color of the UIBarButtonItem's image was the origin image's color.

I doubt that I need to add some code to set some properties of the UIToolBar or UIBarButtonItem if I want to it through writing code. Could you tell me how to do?

like image 484
user2416374 Avatar asked Dec 05 '22 08:12

user2416374


1 Answers

Although it should not be required, my colored UIBarButtonItem since iOS7 are done with:

For 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 is the key here.

For 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
    }

Again, .withRenderingMode(.alwaysOriginal) is the key here.

like image 108
Francois Robert Avatar answered Dec 30 '22 07:12

Francois Robert