如何调整 UINavigationBarAppearance 背景图片的大小

How to resize UINavigationBarAppearance background image

我正在尝试使用 UINavigationBarAppearance 将背景图像添加到我的导航栏。但是,imageView 尺寸大于导航栏内容视图。我该如何解决?

结果:注意图像视图与安全区域重叠

层次结构调试器

代码:

  private func setupNavBar() {
    navigationItem.largeTitleDisplayMode = .never
    guard let navigationController = navigationController else { return }
    let appearance = navigationController.navigationBar.standardAppearance.copy()
    appearance.configureWithTransparentBackground()
    appearance.backgroundImage = UIImage.checkmark
    appearance.backgroundImageContentMode = .scaleAspectFit
    appearance.backgroundColor = .red
    navigationController.navigationBar.standardAppearance = appearance
  }

找到替代方案。我没有使用外观背景图像,而是在导航项上设置了 titleView。

let imageView = UIImageView(image: UIImage.checkmark)
imageView.contentMode = .scaleAspectFit
navigationItem.titleView = imageView