Search code examples
iosswiftuiimageviewstoryboarduinavigationitem

Adding UIImage ignores and resizes UIImageView frame


I'm currently trying to add an image into the navigation item for one view. In the view's viewDidLoad(), a function is called with the following code, similar to this post:

let logo = UIImage(named: "Menu_Logo")

let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 122, height: 26))
imageView.contentMode = .scaleAspectFit
imageView.clipsToBounds = true
imageView.image = logo

self.navigationItem.titleView = imageView

Instead of giving me the expected size however, the view ends up looking like this:

UIImageView expanded Inspector shows the size grew above the defined frame

Removing the UIImage from the UIImageView makes the view sized correctly like this:

UIImageView is sized like expected when no UIImage is set The expected size of 122/26 is displayed when inspecting the view

This seems like strange behaviour to me, especially since I did set the content mode to .scaleAspectFit. Is there something I am forgetting regarding adding an UIImageView as the navigationItem.titleView?


Solution

  • On UINavigationBar, title view takes its full size, if content is large.

    Resize the image rather than UIImageView as following with passing size (122, 26). This will solve your problem.

    func imageResize(sizeChange: CGSize) -> UIImage {
        let hasAlpha = true
        let scale: CGFloat = 0.0 // Use scale factor of main screen
    
        UIGraphicsBeginImageContextWithOptions(sizeChange, !hasAlpha, scale)
        self.draw(in: CGRect(origin: CGPoint.zero, size: sizeChange))
    
        let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
        return scaledImage!
    }