在 swift 中为 UIBarButtonItem 设置背景图像

Setting Background Image for UIBarButtonItem in swift

我正在尝试以编程方式设置 UIBarButtonItem 的背景图像。但是我的图像被拉伸和平铺。解决此问题的任何帮助将不胜感激。这是我的代码

var objectSelected : UIImage!{
    didSet{
        if objectSelected == nil {
            objectSelected = UIImage(named: "line")
        }
       let insets = UIEdgeInsetsMake(0, 0, 10, 0)
        objectSelected.resizableImageWithCapInsets(insets)
      objectSelector.setBackgroundImage(objectSelected, forState: UIControlState.Normal, style: UIBarButtonItemStyle.Plain, barMetrics: UIBarMetrics.Default)

    }
}


@IBOutlet weak var objectSelector: UIBarButtonItem!

你可以试试这个。

    var myBtn: UIButton = UIButton()
    myBtn.setImage(UIImage(named: "line"), forState: .Normal)
    myBtn.frame = CGRectMake(0, 0, 70, 70)
    myBtn.addTarget(self, action: "myBtnAction:", forControlEvents: .TouchUpInside)

    self.navigationItem.setLeftBarButtonItem(UIBarButtonItem(customView: myBtn), animated: true)