Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

uibutton

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)

I have an image that I've set on my button, but I'd like to scale it to be smaller than the button (for example the image should be 50,50) and center in the button. How might I do this in Swift?

like image 593
Shai UI Avatar asked Dec 26 '14 05:12

Shai UI


People also ask

How do you center an image in UIButton?

You must set the content mode for the image inside the UIButton. The solution is to update the contentMode of the Image when you are using a foreground image inside a button along with the contentMode of the UIButton .

How to resize UIButton swift?

In interface builder, holding Command + = will resize a button to fit its text.

What is a UIButton?

A control that executes your custom code in response to user interactions.


2 Answers

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)
}
like image 121
Leo Dabus Avatar answered Sep 29 '22 20:09

Leo Dabus


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
like image 36
Rohan Vasishth Avatar answered Sep 29 '22 20:09

Rohan Vasishth