Swift 5 version of the accepted answer:
let image = UIImage(named: "image_name") as UIImage? let button = UIButton(type: UIButton.ButtonType.custom) as UIButton 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 = .lightGray self.view.addSubview(button)
where of course
@objc func function() {...}
The image is centered by default. You can change this by setting the imageEdgeInsets button, for example:
// In this case image is 40 wide and aligned to the left button.imageEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: button.frame.width - 45)
DeepBlue Jun 21 '19 at 10:00 2019-06-21 10:00
source share