Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add padding-left on a UIButton created programmatically?

I am having a trouble adding left padding on a UIButton. I have a UIButton with UIControlContentHorizontalAlignmentLeft. I want the text to be displayed on the left side but it is too left. when I give the border, it doesn't look good. I would like to give some padding on the text about 5px like in CSS. I googled for the solution but can't find one particularly for UIButton. Thanks in advance for help.

like image 356
MissStack Avatar asked May 14 '12 18:05

MissStack


4 Answers

titleEdgeInsets The inset or outset margins for the edges of the button title drawing rectangle.

@property(nonatomic) UIEdgeInsets titleEdgeInsets

Discussion Use this property to resize and reposition the effective drawing rectangle for the button title. You can specify a different value for each of the four insets (top, left, bottom, right). A positive value shrinks, or insets, that edge—moving it closer to the center of the button. A negative value expands, or outsets, that edge. Use the UIEdgeInsetsMake function to construct a value for this property. The default value is UIEdgeInsetsZero.

Availability Available in iOS 2.0 and later.

Declared In UIButton.h

Give this a try :)

[myButton setTitleEdgeInsets:UIEdgeInsetsMake(0.0, 5.0, 0.0, 0.0)];

Also if you're using a custom button there is such a thing as Content Insets and Image Insets.

Incase you've made it here looking for Swift. This is valid Swift 3.0 😃

myButton.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: 5.0, bottom: 0.0, right: 0.0)

You can set it directly as well. It is helpful if want to use one or two properties.

myButton.titleEdgeInsets.top = 0
myButton.titleEdgeInsets.left = 5
myButton.titleEdgeInsets.bottom = 0
myButton.titleEdgeInsets.right = 0
like image 138
Ryan Poolos Avatar answered Nov 18 '22 05:11

Ryan Poolos


Post Xcode 8 if you want to set it these insets through interface builder (IB),you will find these inset settings in size inspector instead of attribute inspector.

Hope this helps.

enter image description here

like image 28
Vaibhav Avatar answered Nov 18 '22 04:11

Vaibhav


Here is a better answer to:

  • avoid truncating the button title
  • avoid title from extending beyond the button's view
  • make the button frame work well with an image.

Code:

extension UIButton {
    func addLeftPadding(_ padding: CGFloat) {
        titleEdgeInsets = UIEdgeInsets(top: 0.0, left: padding, bottom: 0.0, right: -padding)
        contentEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: padding)
    }
}

Usage:

myButton.addLeftPadding(10)
like image 29
Lucas Chwe Avatar answered Nov 18 '22 04:11

Lucas Chwe


In Xcode 6 you can specify title inset in IB:

Interface builder edge title inset

like image 27
Sergey Demchenko Avatar answered Nov 18 '22 05:11

Sergey Demchenko