1

This is the code I'm using to set an image in the title of the nativation bar,

let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 30))
imageView.contentMode = .scaleAspectFit

let image = UIImage(named: "fullLogo")
imageView.image = image

self.navigationItem.titleView = imageView;

The issue is that image appears a little too big. How do I resize the image in code? I tried many combinations of the width and height but it doesn't seem to work.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Melissa Stewart
  • 3,483
  • 11
  • 49
  • 88

2 Answers2

2

According to documentation:

Custom title views are centered on the navigation bar and may be resized to fit.

That's what happening with your image view. The solution can be to add imageView as subview to UIView and assign UIView to titleView property.

The easier solution may be to set imageView.contentMode to .center but in this case you need to be sure that your fullLogo image is actually 100x30, if it is bigger than titleView frame calculated by iOS your image will overlay navigation bar and view controller's view.

And you can init your UIImageView or container UIView with frame: .zero because it's frame will be recalculated in runtime.

Peter Tretyakov
  • 3,380
  • 6
  • 38
  • 54
1

Set

imageView.clipsToBounds = true

For resizing the image this SO Post would help. Hope this helps.

Happy Coding.

Md. Ibrahim Hassan
  • 5,359
  • 1
  • 25
  • 45