If you have created an UILabel programmatically, replace the UILabel class with the PaddingLabel and add the padding: // Init Label let label = PaddingLabel() label. backgroundColor = . black label.
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. Select the label and click the constraints panel at the bottom right in the Storyboard file.
I am using auto layout. Solution that worked for me was setting UIButton
's contentEdgeInsets
.
button.contentEdgeInsets = UIEdgeInsetsMake(0.0f, 30.0f, 0.0f, 30.0f);
button.contentEdgeInsets = UIEdgeInsets(top: 0.0, left: 30.0, bottom: 0.0, right: 30.0)
Ok the simplest solution I've found so far is:
self.textAlignment = UITextAlignmentCenter;
[self sizeToFit];
CGRect frame = self.frame;
frame.size.width += 20; //l + r padding
self.frame = frame;
Not exactly what I wanted, but it works.
To set padding in UIButton
text you need to use UIButton
's contentEdgeInsets
property.
In Storyboard, to set content inset do following steps:
UIButton
To add padding to UILabel the most flexible approach is to subclass UILabel and add an edgeInsets property. You then set the desired insets and the label will be drawn accordingly.
OSLabel.h
#import <UIKit/UIKit.h>
@interface OSLabel : UILabel
@property (nonatomic, assign) UIEdgeInsets edgeInsets;
@end
OSLabel.m
#import "OSLabel.h"
@implementation OSLabel
- (id)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
self.edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
}
return self;
}
-(id)initWithCoder:(NSCoder *)aDecoder{
self = [super initWithCoder:aDecoder];
if(self){
self.edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
}
return self;
}
- (void)drawTextInRect:(CGRect)rect {
return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.edgeInsets)];
}
@end
On Xcode 9, the insets are now located in the Size Inspector instead of the Attributes Inspector:
Here's a sublass of UILabel that has customizable padding using an edgeInset property:
PaddedLabel.h
#import <UIKit/UIKit.h>
@interface PaddedLabel : UILabel
@property UIEdgeInsets edgeInsets;
@end
PaddedLabel.m
#import "PaddedLabel.h"
@implementation PaddedLabel
-(void)drawTextInRect:(CGRect)rect {
return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.edgeInsets)];
}
-(CGSize)intrinsicContentSize {
CGSize contentSize = [super intrinsicContentSize];
UIEdgeInsets insets = self.edgeInsets;
contentSize.height += insets.top + insets.bottom;
contentSize.width += insets.left + insets.right;
return contentSize;
}
@end
(This is a simplification of Brody's answer which also works with autolayout.)
CGRectInset is your friend. You can set negative 'insets' to create padding:
[self sizeToFit];
CGRect rect = self.frame;
rect = CGRectInset( rect, -6.f, -5.f); // h inset, v inset
self.frame = rect;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With