How to center an image inside an UIButton without stretching in both direction in Swift?

Finally a solution came through. 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.

shiftButton.contentMode = .Center
shiftButton.imageView?.contentMode = .ScaleAspectFit

  • Add User Defined Runtime Attributes to your button.

In the screen shot below value 1 is equal to scaleAspectFit

imageView.ContentMode = scaleAspectFit

enter image description here enter image description here


If you're using storyboard, double-check that you don't have anything set for the button title.