Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Background Image for UIBarButtonItem in swift

I am trying set the background image of UIBarButtonItem programatically. But my image is stretched and tiled. Any help on fixing this would be much appreciated. Here is my code

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!
like image 768
Magesh Avatar asked Mar 16 '23 09:03

Magesh


1 Answers

You could try this.

    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)
like image 62
the_pantless_coder Avatar answered Apr 26 '23 05:04

the_pantless_coder