1

I have this code in order to put an UIImageView in the center of a navigation controller bar and properly scale the image:

override func viewDidAppear(_ animated: Bool) {

    let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 150, height: 28));
    imageView.contentMode = .scaleAspectFit;

    let image = UIImage(named: "image_title.png");
    imageView.image = image;

    self.navigationItem.titleView = imageView;
}

The code works fine in iOS 10, however in iOS 11 the ".scaleAspectFit" property is not considered and the images is not scaled in the UIImageView size.

I tried with some solutions i found:

  • Setting the frame of the UIImageView after setting the "contentMode" property
  • Setting imageView.setNeedsLayout()
  • Setting imageView.setNeedsDisplay()

unfortunately, no one of these solutions works. The "contentMode" property is simply ignored,

Any idea on what the problem could be?

Thank you in advance

Andrea Gorrieri
  • 1,704
  • 2
  • 22
  • 36
  • What have you tried to solve your problem? – Shebuka Sep 25 '17 at 12:57
  • may this help you : https://stackoverflow.com/a/44040208/5580393 – Aditya Sep 25 '17 at 13:08
  • Hi Shebuka, i tried with some proposed solutions i found: . setting the frame of the image after setting the "contentMode" property . setting imageView.setNeedsLayout() . setting imageView.setNeedsDisplay() no one of these solutions works. The strange thing is that my code works fine in iOS 10... – Andrea Gorrieri Sep 25 '17 at 13:33
  • Hi Aditya, thank you for your help, unlikely the proposed solution does not work for me :( – Andrea Gorrieri Sep 25 '17 at 13:37

2 Answers2

6

Works for me such way (using additional UIView)

        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 120, height: 40))
        let image = UIImageView(image: UIImage(named: "img-logo"))
        image.contentMode = .scaleAspectFit
        image.frame = titleView.bounds
        titleView.addSubview(image)
        viewController.navigationItem.titleView = titleView
nerowolfe
  • 4,787
  • 3
  • 20
  • 19
0
    let imageView = UIImageView(image: UIImage(named: "img-logo"))
    imageView.contentMode = .scaleAspectFit
    navigationItem.titleView = imageView
Nilomi Shah
  • 186
  • 7