Change a UIButton's text (padding) programmatically in Swift

KellysOnTop23 picture KellysOnTop23 · Jul 11, 2015 · Viewed 57.7k times · Source

Still learning Swift and don't know Objective-C. I saw that in order to changing a button's text programmatically requires the use of titleEdgeInsets but I am not really sure how to use it.

I would like to change the text in the button (padding) in the bottom and both the left and the right.

Thanks for any responses and/or examples!

Answer

7stud picture 7stud · Jan 9, 2016

Still valid for: iOS 12/Xcode 10/Swift 4.2/OSX 10.13.2


iOS 9.1/Xcode 7.1/Swift 2.1/OSX 10.10.5:

The method titleEdgeInsets didn't work for me. My button's frame tightly hugs the text (I didn't specify a frame size), and the frame has a red background color. After doing:

 myButton.titleEdgeInsets = UIEdgeInsetsMake(10,10,10,10)

the red background shrunk inwards by 10 pixels on each side, which meant that now some of the text was outside the red background. Using negative values had no effect on the original frame size.

I was able to get padding around the text, effectively making the frame bigger, by doing:

myButton.contentEdgeInsets = UIEdgeInsetsMake(5,5,5,5)