Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to aspect fit the bar button image

Tags:

ios

swift

I want to add the image in the navigation bar button.

Here is the image I want to set:

enter image description here

I set it by drag the bar button to the Main.storyboard. Then I set it like this:

@IBOutlet var addNewNoteButton: UIBarButtonItem!

...

let featherImageView = UIImageView()
featherImageView.contentMode = UIViewContentMode.ScaleAspectFit

featherImageView.image = UIImage(named: "feather")?.imageWithRenderingMode(.AlwaysOriginal)
addNewNoteButton.image = featherImageView.image

But it doesn't show the image well:

enter image description here'

I also see somewhere, but they only do with create a button, then assign this button to navigation bar button.

Any help would be appreciated.

like image 468
Khuong Avatar asked Jan 19 '16 12:01

Khuong


1 Answers

You can create a custom button for that. Use below code in your viewDidLoad method.

//create a new button
let button: UIButton = UIButton(type: .Custom)

//set image for button
button.setImage(UIImage(named: "T018d.png"), forState: UIControlState.Normal)

//set frame
button.frame = CGRectMake(0, 0, 53, 31)

let barButton = UIBarButtonItem(customView: button)

//assign button to navigationbar
self.navigationItem.rightBarButtonItem = barButton

And result will be:

enter image description here

If you want to place it left side then replace this line

self.navigationItem.rightBarButtonItem = barButton

with

self.navigationItem.leftBarButtonItem = barButton
like image 156
Dharmesh Kheni Avatar answered Oct 17 '22 18:10

Dharmesh Kheni