向 UINavigationBar 添加一个按钮

Adding a button to the UINavigationBar

我想在我的导航栏中添加图片,但无法正确完成。这是代码:

@IBOutlet weak var btnStateChange: UIBarButtonItem!
    let buttonState: UIButton = UIButton(type: .Custom)
    buttonState.setImage(UIImage(named: "Button-State.png"), forState: UIControlState.Normal)
    buttonState.addTarget(self, action: nil, forControlEvents: .TouchUpInside)
    buttonState.frame = CGRectMake(0, 0, 22, 22)
    
    let barButton = UIBarButtonItem(customView: buttonState)
    self.btnStateChange = barButton

它应该是这样的:

但我得到了这个结果:

我需要更改代码吗?或者它可能是我使用的 PNG?

如果绿色是 png 图像的一部分,您可能需要将 UIImage 的渲染模式设置为 .AlwaysOriginal

let buttonState: UIButton = UIButton(type: .Custom)
buttonState.setImage(UIImage(named: "Button-State.png")?.imageWithRenderingMode(.AlwaysOriginal), forState: UIControlState.Normal)
buttonState.addTarget(self, action: nil, forControlEvents: .TouchUpInside)
buttonState.frame = CGRectMake(0, 0, 22, 22)