Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem adding an image to the toolbar using UIBarButtonItem, displaying blank white box instead of image

Im not sure what im doing wrong. The file name is correct, the style is set to plain. But Im getting a bank white box the size of my image. Im using UINavigationController.

Please assist and thank you thank you in advance.

**FYI I am sorta new to objective c so dont be too hard on me. ;)

 UIBarButtonItem *toolbarChannelGuideButton = [[UIBarButtonItem alloc]
     initWithImage:[UIImage imageNamed:@"channel-guide-button.png"]
     style:UIBarButtonItemStylePlain
     target:self
     action:@selector(action:)];


self.toolbarItems = [NSArray arrayWithObjects:toolbarChannelGuideButton, nil];
[toolbarChannelGuideButton release];
like image 856
Jordan Brown Avatar asked Oct 26 '10 23:10

Jordan Brown


Video Answer


2 Answers

The reason it was creating the white mask was because the UIToolBar doesnt allow color images on it by default. The way to accomplish this is creating a UIImage then assign a UIButton to that image. Then create a UIBarButton using initWithCustomView with the UIButton as the custom view.

Code:

     //Load the image   
     UIImage *buttonImage = [UIImage imageNamed:@"your-image.png"];

     //create the button and assign the image
     UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
     [button setImage:buttonImage forState:UIControlStateNormal];

     //sets the frame of the button to the size of the image
     button.frame = CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height);

     //creates a UIBarButtonItem with the button as a custom view
     UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];



     self.toolbarItems = [NSArray arrayWithObjects:customBarItem, nil];
     [customBarItem release];
like image 183
Jordan Brown Avatar answered Nov 15 '22 01:11

Jordan Brown


Starting with iOS 7 you can use below:

 UIImage *image = [[UIImage imageNamed:@"myImage.png"];
 imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
 UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(YOUR_METHOD:)];
like image 38
ShivaPrasad Avatar answered Nov 15 '22 01:11

ShivaPrasad