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

时间:2018-04-13 09:34:55

标签: ios swift uiimageview storyboard uinavigationitem

我目前正在尝试将图像添加到一个视图的导航项中。在视图的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 expanded Inspector shows the size grew above the defined frame

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

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

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

,我有什么遗漏

1 个答案:

答案 0 :(得分:1)

UINavigationBar上,如果内容很大,标题视图将采用其完整大小。

  

通过尺寸(122,26)调整图像大小而不是UIImageView。这将解决您的问题。

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