ios - 在 iOS 导航 Controller 的代码中自定义图像大小

标签 ios swift uiimageview uinavigationbar

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

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;

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

最佳答案

根据 documentation :

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

这就是您的 ImageView 所发生的情况。解决方案可以是将 imageView 作为 subview 添加到 UIView 并将 UIView 分配给 titleView 属性。

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

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

关于ios - 在 iOS 导航 Controller 的代码中自定义图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52842006/

相关文章:

ios - 检查 View 是否在其他 View 中?

ios - 如何在同一个 ViewController 中推送到不同的 UITableView 并导航回第一个 UITableView?

objective-c - Objective - C,在 UIImageView 中显示图像序列的最快方法

ios - 解析 Swift 文档?

ios - 在 iOS 中通过蓝牙或 wifi 发送文件

ios - 在 Swift 中用特定颜色绘制路径/矩形有什么等价的

ios - 如何编写可以在 Objective C 中使用的带有 throws 语句和返回值的 swift 3 方法?

iOS:使用 UIImageView 进行动画

ios - UICollectionViewCell 中圆形 UIImageView 的错误

ios - 使用音频录制的URL连续播放音频文件