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

时间:2017-08-04 21:05:55

标签: ios image button uinavigationbar uinavigationitem

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

方法1:

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

看起来像这样:

Method 1

方法2:

    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)

看起来像这样:

Method 2

方法3:

    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)

看起来像这样:

Method 3

你可以看到标题已经消失。

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

UI Hierarchy

按钮似乎占据了导航栏中的所有空格。

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

System item

有谁知道这个问题的原因?我想我的想法已经用完了。

3 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:3)

尝试将其添加为subView,而不是将其设置为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)

答案 2 :(得分:1)

根据我的经验,您遇到了这个问题,因为您为所有resolution 1X, 2X and 3X添加了大尺寸图像。你需要 将其缩小到更适合导航栏的大小。

解决方案:1

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

的图片尺寸

asset @ 1X大小:24X24

asset @ 2X大小:48X48

asset @ 3X大小:72X72

解决方案:2

如果要使用相同的图像,则需要在代码中进行以下更改。

您只需要在UIImageView内添加UIView,然后将所有内容 按预期工作。

代码:

    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
相关问题