Tiois
Tiois

Reputation: 1559

Can't see my navigationbar custom button, but it is clickable

I want to add a custom button (to the right) in my navigation bar.

I have the following code in my "viewDidLoad" function :

UIButton *audioBtn = [[UIButton alloc] init];
[audioBtn setTitle:@"Play" forState:UIControlStateNormal];

UIImage *buttonImage = [UIImage imageNamed:@"play.png"];
[audioBtn setBackgroundImage:buttonImage forState:UIControlStateNormal];

[audioBtn addTarget:self action:@selector(toggleAudioPlayback:) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithCustomView:audioBtn];
self.navigationItem.rightBarButtonItem = button;

[audioBtn release];
[button release];

I can't see the button in my navigation bar, but if I click to the right (where the button is supposed to be), it triggers the function "toggleAudioPlayback", so the only problem is that I don't see the button!

I tried with different image, setting a background color, nothing works...

By the way, I use this image somewhere else in the code, and I see it (on a custom button, but not in a navigationBar).

Help me please!

Upvotes: 4

Views: 664

Answers (2)

theChrisKent
theChrisKent

Reputation: 15099

Make your life easier and instead of a customView just use a UIBarButtonItem with a custom image:

    UIBarButtonItem *audioBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"play.png"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleAudioPlayback:)];
    self.navigationItem.rightBarButtonItem = audioBtn;
    [audioBtn release];

UPDATE

Since you have indicated you want your button to not have a border, then you will need to use a CustomView afterall, but I have modified your code to make this work (the key difference is the assigning of the frame, which is set to the size of the image, but you could set it to a custom size to have the image centered):

UIButton *audioBtn = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *playImg = [UIImage imageNamed:@"play.png"];
[audioButton setBackgroundImage:playImg forState:UIControlStateNormal];
[audioButton setBackgroundImage:playImg forState:UIControlStateHighlighted];
audioBtn.frame = CGRectMake(0,0,playImg.size.width,playImg.size.height);
[audioBtn addTarget:self action:@selector(toggleAudioPlayback:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithCustomView:audioBtn];
self.navigationItem.rightBarButtonItem = button;
[audioBtn release];
[button release];

Upvotes: 2

Simon Goldeen
Simon Goldeen

Reputation: 9080

Instead of [[UIButton alloc] init] try the +buttonWithType: method on UIButton.

Upvotes: 0

Related Questions