How to set image on rightBarButtonItem UINavigationBar?

I am trying to set the image to rightBarButtonItem and its beautiful, but the only thing that is wrong is the background behind this image, which is wider than my image. Does anyone know how to fix this. The code:

[self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"action_btn.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(actionButtonClicked:)] animated:YES]; 
+8
objective-c iphone uinavigationbar
source share
3 answers

Here you can set the image to 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 more questions.

+18
source share

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) 

PS The constructor of UIBarButtonItem(image:style:target:action:) works only for transparent PNG, I also need to set the tintcolor button other than clearColor.

+2
source share

Im not in Xcode at the moment, so I can not send the code. The procedure is as follows

  • Create UIBarButtonItem with default initializer
  • Create UIImage
  • Get CGRect from image sizes,
  • Set UIBarButtonItem.frame to dimensions

If it does not match 100%, consider adding button borders to image sizes before setting the button frame

-one
source share

All Articles