It is not possible to see my custom navigation button, but it is viewable.

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 on the right (where the button should be), it launches the “toggleAudioPlayback” function, so the only problem is that I don’t see the button!

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

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

Help me please!

+4
source share
2 answers

Make your life easier, and instead of 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 indicated that you want your button to have no border, you will need to use the CustomView afterall function, but I changed your code to make this work (the key difference is to assign a frame that set the image size, but you can set it to custom size to center the image):

 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]; 
+2
source

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

0
source

Source: https://habr.com/ru/post/1342736/


All Articles