How to scale image and center it on a UIButton in Swift?

Xcode 8.3.1 • Swift 3.1

let button = UIButton(type: .custom)
let image = UIImage(named: "myimage.png")

func buttonTouchDown(_ button: UIButton) {
    print("button Touch Down")
}

override func viewDidLoad() {
    super.viewDidLoad()
    button.frame = CGRect(x: 0, y: 0 , width: 100, height: 100)
    button.backgroundColor = .clear
    button.addTarget(self, action: #selector(buttonTouchDown), for: .touchDown)
    button.setTitle("Title", for: .normal)
    button.setTitleColor(.black, for: .normal)
    button.setImage(image, for: .normal)
    button.imageEdgeInsets = UIEdgeInsetsMake(25,25,25,25)
    view.addSubview(button)
}

Or via XIB after selecting your UIButton.

Just make sure your insets are all the same.


enter image description here


Swift 5, Swift 4, Swift 3

var image = UIImage(named: "myimage") as UIImage!   
btnetc.setImage(image, for: .normal)
btnetc.imageView?.contentMode = .scaleAspectFill

or

btnetc.imageView?.contentMode = .scaleAspectFit

or

btnetc.imageView?.contentMode = .scaleToFill

Ther is a much easier way to do this where you don't have to deal with content insets. Here its is:

var button = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
var image = UIImage(named: "myimage.png") as UIImage!
button.frame = CGRectMake(0, 0, 100, 100)
button.setImage(image, forState: .Normal)
button.contentMode = .center
button.imageView?.contentMode = .scaleAspectFit

Tags:

Uibutton

Swift