I\'ve got various views in my iPhone application that require padding e.g a custom UIButton with text aligned left, and a UILabel with a background color.
This may be a
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 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
To set padding in UIButton
text you need to use UIButton
's contentEdgeInsets
property.
In Storyboard, to set content inset do following steps:
UIButton
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;