iosswift3uiimageviewios11contentmode

Setting content mode in UIImageView no longer works in iOS 11


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:

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


Solution

  • 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