image for nav bar button item swift

user2363025 picture user2363025 · Jul 17, 2015 · Viewed 38.7k times · Source

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.

Answer

Avijit Nagare picture Avijit Nagare · Jul 17, 2015

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
 }