Monday, March 7, 2011

How to add padding to a UIButton's title

I had a situation where I needed to add padding to a UIButton in an iOS app. I searched around and found some whonky solutions and workarounds, then I discovered there is simply titleEdgeInsets, available since iPhone SDK 2.0. used like so...



button1.titleEdgeInsets=UIEdgeInsetsMake(0, 5, 0, 5);


where button1 is a UIButton. The default values is UIEdgeInsetsZero.

The other thing to know is that the order for the values is TOP LEFT BOTTOM RIGHT.
This is opposite of the way we do it in CSS.

Also look out for the following other UIButton properties which accomplish similar padding tasks:

@property contentEdgeInsets
@property imageEdgeInsets


And there's that.

2 comments:

  1. How can I also pad the inside of a UILabel?

    ReplyDelete
  2. for a UILabel, i'd probably just make the frame smaller than the space, which will give the illusion of padding.

    e.g., if you had a 320x40 label (positioned at coordinates 0,100 for this example), created like this:
    UILabel *label ==[[UILabel alloc]initWithFrame:CGRectMake(0,100,320,40)];

    ...and if you wanted 10px of padding on the left and right, you could change the way you create your uilabel to this...
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10,100,300,40)];

    the width of 300px takes into account 10px of padding on the left and 10px of padding on the right.
    i hope this helps!

    ReplyDelete