添加 UIImage 会忽略 UIImageView 框架并调整其大小

Adding UIImage ignores and resizes UIImageView frame

我目前正在尝试将图像添加到一个视图的导航项中。在view的viewDidLoad()中调用了一个函数,代码如下,类似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

然而,视图并没有给我预期的大小,而是看起来像这样:

从 UIImageView 中删除 UIImage 使视图大小正确,如下所示:

这对我来说似乎很奇怪,特别是因为我确实将内容模式设置为 .scaleAspectFit。关于将 UIImageView 添加为 navigationItem.titleView,我是否忘记了什么?

UINavigationBar 上,如果内容很大,标题视图会显示完整大小。

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