How to set the image on rightBarButtonItem of UINavigationBar?

13,338

Solution 1

Here you can set the image on rightBarButtonItem of NavigationBar as follows:

UIButton *button1 = [[UIButton alloc] init];
button1.frame=CGRectMake(0,0,105,30);
[button1 setBackgroundImage:[UIImage imageNamed: @"image1.png"] forState:UIControlStateNormal];
[button1 addTarget:appDelegate action:@selector(Open_Link1) forControlEvents:UIControlEventTouchUpInside];

self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button1];
[button1 release];

Please let me know if you have any more questions.

Solution 2

In Swift:

let infoImage = UIImage(named: "my-icon")
let imgWidth = infoImage?.size.width
let imgHeight = infoImage?.size.height
let button:UIButton = UIButton(frame: CGRect(x: 0,y: 0,width: imgWidth!, height: imgHeight!))
button.setBackgroundImage(infoImage, forState: .Normal)
button.addTarget(self, action: Selector("openInfo"), forControlEvents: UIControlEvents.TouchUpInside)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)

P.S. UIBarButtonItem(image:style:target:action:) constructor only works for transparent PNG, also I had to set button tintcolor other than clearColor.

Share:
13,338

Related videos on Youtube

Ashutosh
Author by

Ashutosh

Updated on June 04, 2022

Comments

  • Ashutosh
    Ashutosh over 1 year

    I am trying to set the image on rightBarButtonItem and its fine but the only thing wrong is the background behind this image which has more width than my image. Anybody has any idea how to fix this. Code:

    [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"action_btn.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(actionButtonClicked:)] animated:YES];
    
  • Ashutosh
    Ashutosh over 12 years
    I don't see any property to set the frame of this button. A little bit of code would be very helpful
  • AppAspect
    AppAspect over 12 years
    Here you can try this and It is working for me and I am sure will definitely work for you and you can take necessary actions when it works.
  • AppAspect
    AppAspect over 12 years
    Thanks for the actions. Let me know if you need more help.