Setting content mode in UIImageView no longer works in iOS 11

1.9k Views Asked by At

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

2

There are 2 best solutions below

2
nerowolfe On BEST ANSWER

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
0
Nilomi Shah On
    let imageView = UIImageView(image: UIImage(named: "img-logo"))
    imageView.contentMode = .scaleAspectFit
    navigationItem.titleView = imageView