3

I am trying to add an image to the navigation bar by:

let image = UIImage(named: "my-image")
navigationItem.titleView = UIImageView(image: image)

But nothing happens, what am I doing wrong?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Kiwo Tew
  • 1,491
  • 1
  • 22
  • 39
  • Are you sure that you are getting the correct navigation item, and that the image exists? – Kendel Aug 02 '15 at 00:33
  • 1
    `navigationItem.titleView.sizeToFit()` – pronebird Aug 02 '15 at 00:33
  • @Andy The image exist yeah. In storyboard its setup as: Navigationcontroller->tableview. And in the tableview I am trying to edit the image. Also if I click on some item in the tableview then go back again the println() for the image is shown but the image its not, but how come it don't show the first time? – Kiwo Tew Aug 02 '15 at 00:37
  • @Andy sizeToFit() made it work. Thanks! – Kiwo Tew Aug 02 '15 at 00:38
  • @KiwoTew IIRC UINavigationController does not resize custom titleView itself. I guess UIImageView was created with zero dimensions. – pronebird Aug 02 '15 at 00:42

1 Answers1

3
    let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 39, height: 39))
    imageView.contentMode = .ScaleAspectFit
    let image = UIImage(named: "newlogo.jpg")
    imageView.image = image
    navigationItem.titleView = imageView