bigpotato
bigpotato

Reputation: 27507

Xcode: How to add margin/padding to label text?

I have a label with text:

enter image description here

However, I want it have more padding (and for the edges to be a little rounded if possible). But when I stretch the label in my storyboard so that it appears to have padding, and then I restart the simulator, it doesn't add padding to it.

How would I do this? BTW, I'm using auto layout + objective c

Upvotes: 16

Views: 43080

Answers (5)

Dangerous Cat
Dangerous Cat

Reputation: 21

To change the padding on a label with a background color where text is aligned left or right, first select the label then in the attributes inspector at the top and change text from Plain to Attributed in the dropdown menu

Select the alignment of the text (in this example it aligns right) click on the 3 dot menu button to the far right to open additional settings and change Text-Direction from Natural to Right To Left

Text in label should now have a bit of padding on the right side

Upvotes: 2

Francisco Medina
Francisco Medina

Reputation: 363

You can add round corners from storyboard select your UILabel (or any view) and go to inspector, on the identity inspector section add a value as shown in the picture.

enter image description here

Upvotes: 6

the_critic
the_critic

Reputation: 12820

If you want to go the layout constraints route, this is probably the fitting solution for you:

You should use a container view and place the label inside of that. Then add constraints for the label, which will be equivalent to a padding.

enter image description here

Select the label and click the constraints panel at the bottom right in the Storyboard file.

Label's constraints to container view

With the label selected, apply layout constraints like seen above (make sure you select the red "lines" so that the constraints are actually applied).

End result

The orange view is the container view. The label is right inside of that.

Upvotes: 24

Andrey
Andrey

Reputation: 2729

You need to override UILabel's drawRect method

Sample code:

#import "OCPaddedLabel.h"
#define PAD 10.0f
#define PAD_VERT 6.0f

@implementation OCPaddedLabel

- (void)drawTextInRect:(CGRect)rect {
    UIEdgeInsets insets = {PAD_VERT, PAD, PAD_VERT, PAD};
    [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}

if you would like to add rounded corners, you need:

label.layer.cornerRadius = 15.0f;
label.layer.masksToBounds = YES;

Upvotes: 3

Josué H.
Josué H.

Reputation: 1191

You can add margin with

yourLabel.frame = CGRectMake(0,0,100,100)

Upvotes: 1

Related Questions