在 iOS 导航控制器中的代码中自定义图像大小

Customizing image size in code in iOS navigation controller

这是我用来在导航栏标题中设置图像的代码,

let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 30))
imageView.contentMode = .scaleAspectFit

let image = UIImage(named: "fullLogo")
imageView.image = image

self.navigationItem.titleView = imageView;

问题是图像看起来有点太大。如何在代码中调整图像大小?我尝试了多种宽度和高度的组合,但似乎不起作用。

设置

imageView.clipsToBounds = true

对于调整图像大小,此 会有所帮助。希望这可以帮助。

快乐编码。

根据documentation

Custom title views are centered on the navigation bar and may be resized to fit.

这就是您的图像视图发生的情况。解决方案可以是将 imageView 作为子视图添加到 UIView 并将 UIView 分配给 titleView 属性.

更简单的解决方案可能是将 imageView.contentMode 设置为 .center,但在这种情况下,您需要确保 fullLogo 图片实际上是 100x30,如果它大于 titleView 由 iOS 计算的框架,您的图像将覆盖导航栏和视图控制器的视图。

并且您可以使用 frame: .zero 初始化 UIImageView 或容器 UIView,因为它的帧将在运行时重新计算。