Jason
Jason

Reputation: 2455

Iphone Interface Builder - Toolbar Image always displays as white box

I am trying to use my own custom image to represent my toolbar buttons, however, whenever I set the image (a png image) as the toolbar button's image, it just displays as a white box the size of the image on my button.

Programmatically I tried this:

bestButton.image = [UIImage imageNamed:@"best_off.png"];

Where bestButton is a UIBarButtonItem declared and set as a property and IBOutlet.

However, this also just displays a white box where the button should be.

To check if the image is bonked, I tried this code:

self.navigationItem.titleView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"best_off.png"]]autorelease];

Which correctly sets my titleview in the navigation bar to show the image perfectly.

Can anyone help identify why this, and all my other images just show as white boxes when put in the bar button's image?

Upvotes: 0

Views: 951

Answers (3)

Nay
Nay

Reputation: 727

You can create customView of UIBarButtonItem and assign to navigationItem. Here is the example...

UIImage *bestImage = [UIImage imageNamed:@"best_off.png"];
UIImageView *bestView = [[UIImageView alloc] initWithImage:bestImage];

UIBarButtonItem *bestButton = [[UIBarButtonItem alloc] init];
bestButton.customView = bestView;
self.navigationItem.rightBarButtonItem = bestButton;

Upvotes: 0

user1215284
user1215284

Reputation: 41

I did this by iterating over all of the bar-items in the toolbar and for those items that were a button, not a space, I set the customView to that of a new button with my image and hooked up the same TouchUpInside listener that I used for the corresponding toolbar button. The buttons even glow. The images have to be 30x30.

If you dont mind looking at MonoTouch instead of Objective C, here is the code. It could be translated easily to Obj C.

void InitializeTbButtons (UIToolbar toolbar, string[] imageFilePaths, EventHandler[] buttonHandlers)
{

int i =0;
foreach (UIBarButtonItem item in toolbar.Items)
{
    if ((item.Image != null) && (( i < imageFilePaths.Length) && (i < buttonHandlers.Length) ) )
    {
        UIButton btn = new UIButton( new System.Drawing.RectangleF(0,0,30,30) );
        string filePath = imageFilePaths[i];
        btn.SetImage( UIImage.FromFile(filePath), UIControlState.Normal );
        btn.ShowsTouchWhenHighlighted = true;
        EventHandler eventHandler = buttonHandlers[i];
        btn.TouchUpInside += eventHandler;
        item.CustomView = btn;
        i++;
    }
}

}

Upvotes: 1

mlewis54
mlewis54

Reputation: 2380

The images used in toolbars are never displayed. They are used as a mask (the alpha channel I believe). Try this. Create an icon (png) with transparent background. Where ever you have a pixel set, it will be white in your icon displayed in the toolbar.

Upvotes: 1

Related Questions