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.
There is a way to use images of different sizes, depending on the device. It's called an Asset Catalog. You'll probably already have one in your project, or if not, you can add one with
File > New > File > Resource > Asset Catalogue
.Within your Asset Catalog, you can have multiple 'Image Sets' (these will be shown down the left-hand side). 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. The correct image will be loaded, depending on the device.Hope this helps!
Try This
For Swift 3
Here is action
Use this code:
Output: