开发者

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

开发者 https://www.devze.com 2023-01-21 22:37 出处:网络
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.

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 d开发者_开发知识库ont 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];


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


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:)];


Does channel-guide-button.png belong to project?

You could break this out like this:

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

or just check your project ;-)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号