Create a button programmatically and set a background image Create a button programmatically and set a background image swift swift

Create a button programmatically and set a background image


Your code should look like below

let image = UIImage(named: "name") as UIImage?let button   = UIButton(type: UIButtonType.Custom) as UIButtonbutton.frame = CGRectMake(100, 100, 100, 100)button.setImage(image, forState: .Normal)button.addTarget(self, action: "btnTouched:", forControlEvents:.TouchUpInside)self.view.addSubview(button)


Try below:

let image = UIImage(named: "ImageName.png") as UIImagevar button   = UIButton.buttonWithType(UIButtonType.System) as UIButtonbutton.frame = CGRectMake(100, 100, 100, 100)button .setBackgroundImage(image, forState: UIControlState.Normal)button.addTarget(self, action: "Action:", forControlEvents:UIControlEvents.TouchUpInside)menuView.addSubview(button)

Let me know whether if it works or not?


Swift 5 version of accepted answer:

let image = UIImage(named: "image_name")let button = UIButton(type: UIButton.ButtonType.custom)button.frame = CGRect(x: 100, y: 100, width: 200, height: 100)button.setImage(image, for: .normal)button.addTarget(self, action: #selector(function), for: .touchUpInside)//button.backgroundColor = .lightGrayself.view.addSubview(button)

where of course

@objc func function() {...}

The image is aligned to center by default. You can change this by setting button's imageEdgeInsets, like this:

// In this case image is 40 wide and aligned to the leftbutton.imageEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: button.frame.width - 45)