How to set the icon on the button in ios using Swift?

enter image description here

    let icon = UIImage(named: "bmiCalculator")!
    button.setImage(icon, for: .normal)
    button.imageView?.contentMode = .scaleAspectFit
    button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -20, bottom: 0, right: 0)

UIEdgeInsets

The inset distances for views. Edge inset values are applied to a rectangle to shrink or expand the area represented by that rectangle. Typically, edge insets are used during view layout to modify the view’s frame. Positive values cause the frame to be inset (or shrunk) by the specified amount. Negative values cause the frame to be outset (or expanded) by the specified amount.


Via code in Swift 3 and Swift 4:

yourButton.setImage(UIImage(named: "imgName"), for: .normal)

or for the background image:

yourButton.setBackgroundImage(UIImage(named: "imgName"), for: .normal)

Via storyboard:

You can also set the icon for a button via the storyboard, setting the image in the attributes inspector of a button element. If you want to have a title over your image set your image in background of the attribute inspector

enter image description here

Question from the comments

how do you put the image alongside the "button" text?

You can do that via code for example by setting the imageEdgeInsets of the button. The example below places the image to the right from the text

yourButton.setImage(UIImage(named: “imgNameWhichYouWantToSetAlongsideTheButton"), for: .normal)
yourButton.imageEdgeInsets = UIEdgeInsets(top: 3, left: 0, bottom: 0, right: -8)