为什么自定义导航栏按钮图像会被拉伸?

Why is custom navigation bar button image stretched?

我尝试添加带有自定义图像的导航栏按钮。但是,无论我使用什么方法,图像总是显得拉伸。

方法一:

    let barbuttonitem = UIBarButtonItem(image: UIImage(named: "apps_small"), style: .plain, target: self, action: nil)
    navigationItem.leftBarButtonItem = barbuttonitem

看起来像这样:

方法二:

    let button = UIButton(type: .custom)
    button.setImage(UIImage(named: "apps_small"), for: .normal)
    button.addTarget(self, action: #selector(TeachingRootViewController.appsTouched), for: .touchUpInside)
    button.frame = CGRect(x: 0, y: 0, width: 10, height: 10)
    button.bounds = CGRect(x: 0, y: 0, width: 10, height: 10)
    navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)

看起来像这样:

方法三:

    let button = UIButton(type: .custom)
    button.setImage(UIImage(named: "apps_small"), for: .normal)
    button.setTitle("Button", for: .normal)
    button.frame = CGRect(x: 0, y: 0, width: 10, height: 10)
    button.bounds = CGRect(x: 0, y: 0, width: 10, height: 10)
    button.imageEdgeInsets = .init(top: 5, left: 5, bottom: 5, right: 300)
    navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)
    navigationItem.leftBarButtonItem?.imageInsets = .init(top: 5, left: 5, bottom: 5, right: 300)

看起来像这样:

如您所见,标题不见了。

在 UI 层次结构中,它看起来像这样:

看来该按钮已占满导航栏中的所有空间。

但是,带有系统项的按钮没有问题:

有谁知道这个问题的原因吗?我想我 运行 没主意了。

尝试将其添加为子视图而不是将其设置为 leftBarButtonItem

var leftButton = UIButton(frame:CGRect(x: 0, y: 0, width: 10, height: 10))
var background = UIImageView(image: UIImage(named: "apps_small"))
background.frame = CGRect(x: 0, y: 0, width: 10, height: 10)
leftButton.addSubview(background)
self.navigationController.navigationBar.addSubview(leftButton)

以上答案是一种解决方法,并非正确的解决方法。 正确答案是您应该生成尺寸正确的照片

  • asset@1x: 22x22px
  • asset@2x: 44x44px
  • asset@3x: 66x66px

As per my experience, You have faced this issue because you're added large size images for all resolution 1X, 2X and 3X. You need to scale it down to a size more appropriate for the navigation bar.

解法:1

您需要将其缩小到更适合导航栏的大小。请查看 UINavigationBar

的图片尺寸

asset@1X Size: 24X24

asset@2X Size: 48X48

asset@3X Size: 72X72

解法:2

如果您想使用相同的图片,则需要对代码进行以下更改。

你只需要在 UIView 中添加 UIImageView 然后一切 按预期工作。

代码:

    let containerView = UIControl(frame: CGRect.init(x: 0, y: 0, width: 30, height: 30))
    containerView.addTarget(self, action: #selector(handleSearch), for: .touchUpInside)
    let imageSearch = UIImageView(frame: CGRect.init(x: 0, y: 0, width: 30, height: 30))
    imageSearch.image = UIImage(named: "search")
    containerView.addSubview(imageSearch)                
    let searchBarButtonItem = UIBarButtonItem(customView: containerView)
    navigationItem.rightBarButtonItem = searchBarButtonItem