UIImage not fitting in UIImageView frame

I have attached a UIImageView to my Navigation bar title view, however the image exceeds the frame no matter which values I input.

Here is the code:

    override func viewDidLayoutSubviews() {
        // style the navbar
        let iconView = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 30))
        let image = UIImage(named: "fresh-appbar")!
        iconView.contentMode = .scaleAspectFit
        iconView.image = image
        navigationItem.titleView = iconView
    }

I have also attached an image:

I'm assuming the image is larger than the 100x30 that you want it to display as. For various reasons, the title view sizing logic when not using auto layout is fairly complex and that may be what your running into.

Instead if you use auto layout to request the size you want, this should be trivial:

let iconView = UIImageView(image: UIImage(named: "fresh-appbar"))
iconView.contentMode = .scaleAspectFit
iconView.widthAnchor.constraint(equalToConstant:100).active = true
iconView.heightAnchor.constraint(equalToConstant:30).active = true
iconView.translatesAutoresizingMaskIntoConstraints = false
navigationItem.titleView = iconView
UIImage not fitting in UIImageView frame
 
 
Q