Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

image for nav bar button item swift

Tags:

I want to display an image in the left hand side of my nav bar in swift.

I have tried adding a nav bar button item and setting an image there.

The problem is that I have to use a really small image for it to fit in the nav bar nicely. But making such a small image leads to pixelation especially on the bigger phone iPhone 6 and 6 Plus.

Is there a way to use a good quality image and then set the frame to fit within the bounds of the nav bar?

My attempt:

var image = UIImage(named: "Harp.png")  image = image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)  self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: image, style: UIBarButtonItemStyle.Plain, target: nil, action: nil) self.navigationItem.leftBarButtonItem.frame = CGRectMake(0, 0, 53, 31) //image.frame = CGRectMake(0, 0, 53, 31) 

I tried putting the frame on the image first and then on the bar button item. But this is throwing up an error:

Type of expression is ambiguous without more context.

like image 775
user2363025 Avatar asked Jul 17 '15 10:07

user2363025


People also ask

How to add custom image in navigation bar button item Swift?

Add a new Image Set with the '+' at the bottom. For each Image Set, you can supply different images (e.g. of different sizes) for each of @1x, @2x, and @3x. Then, to use one of these images in code, you simply use UIImage(named: "name_of_image_set") - note no extension.


1 Answers

Try This

let button = UIButton(type: UIButtonType.Custom) button.setImage(UIImage(named: "yourImageName.png"), forState: UIControlState.Normal) button.addTarget(self, action:Selector("callMethod"), forControlEvents: UIControlEvents.TouchDragInside) button.frame=CGRectMake(0, 0, 30, 30) let barButton = UIBarButtonItem(customView: button) self.navigationItem.leftBarButtonItems = [newBackButton,barButton] 

For Swift 3

let button = UIButton.init(type: .custom) button.setImage(UIImage.init(named: "yourImageName.png"), for: UIControlState.normal) button.addTarget(self, action:#selector(ViewController.callMethod), for:.touchUpInside) button.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30) //CGRectMake(0, 0, 30, 30) let barButton = UIBarButtonItem.init(customView: button)             self.navigationItem.leftBarButtonItem = barButton 

Swift 4

let button = UIButton(type: UIButton.ButtonType.custom) button.setImage(UIImage(named: "getstarted"), for: .normal) button.addTarget(self, action:#selector(callMethod), for: .touchDragInside) button.frame = CGRect(x: 0, y: 0, width: 30, height: 30) let barButton = UIBarButtonItem(customView: button) self.navigationItem.leftBarButtonItems = [barButton] 

Here is action

@objc func callMethod() {        //do stuff here  } 
like image 129
Avijit Nagare Avatar answered Nov 16 '22 00:11

Avijit Nagare