Adding UIImage ignores and resizes UIImageView frame

前提是你 提交于 2019-12-11 02:33:41

问题


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:

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

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?


回答1:


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!
}


来源:https://stackoverflow.com/questions/49813761/adding-uiimage-ignores-and-resizes-uiimageview-frame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!