Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is custom navigation bar button image stretched?

I tried to add a navigation bar button with custom image. However, whatever method I use, the image always appears stretched.

Method 1:

    let barbuttonitem = UIBarButtonItem(image: UIImage(named: "apps_small"), style: .plain, target: self, action: nil)
    navigationItem.leftBarButtonItem = barbuttonitem

It appears like this:

Method 1

Method 2:

    let button = UIButton(type: .custom)
    button.setImage(UIImage(named: "apps_small"), for: .normal)
    button.addTarget(self, action: #selector(TeachingRootViewController.appsTouched), for: .touchUpInside)
    button.frame = CGRect(x: 0, y: 0, width: 10, height: 10)
    button.bounds = CGRect(x: 0, y: 0, width: 10, height: 10)
    navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)

It appears like this:

Method 2

Method 3:

    let button = UIButton(type: .custom)
    button.setImage(UIImage(named: "apps_small"), for: .normal)
    button.setTitle("Button", for: .normal)
    button.frame = CGRect(x: 0, y: 0, width: 10, height: 10)
    button.bounds = CGRect(x: 0, y: 0, width: 10, height: 10)
    button.imageEdgeInsets = .init(top: 5, left: 5, bottom: 5, right: 300)
    navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)
    navigationItem.leftBarButtonItem?.imageInsets = .init(top: 5, left: 5, bottom: 5, right: 300)

It looks like this:

Method 3

As you can see the title is gone.

In the UI Hierarchy, it looks like this:

UI Hierarchy

It appears that the button has taken up all spaces in the navigation bar.

However, there is no problem for button with a system item:

System item

Is there anybody who knows the reason for this problem? I think I have run out of ideas.

like image 796
imxieyi Avatar asked Aug 04 '17 21:08

imxieyi


2 Answers

The above answer is a workaround and not a proper fix. The correct answer is you should have generate your photos with the correct sizes

  • asset@1x: 22x22px
  • asset@2x: 44x44px
  • asset@3x: 66x66px
like image 83
XcodeNOOB Avatar answered Oct 18 '22 21:10

XcodeNOOB


Try adding it as a subView instead of setting it as the leftBarButtonItem

var leftButton = UIButton(frame:CGRect(x: 0, y: 0, width: 10, height: 10))
var background = UIImageView(image: UIImage(named: "apps_small"))
background.frame = CGRect(x: 0, y: 0, width: 10, height: 10)
leftButton.addSubview(background)
self.navigationController.navigationBar.addSubview(leftButton)
like image 3
Marcio Romero Patrnogic Avatar answered Oct 18 '22 21:10

Marcio Romero Patrnogic