I had several problems with the answers here, for example, when you added to the fill, the width of the contents overflowed the box and that I needed a corner in radius. I solved this using the following subclass of UILabel:
#import "MyLabel.h" #define PADDING 8.0 #define CORNER_RADIUS 4.0 @implementation MyLabel - (void)drawRect:(CGRect)rect { self.layer.masksToBounds = YES; self.layer.cornerRadius = CORNER_RADIUS; UIEdgeInsets insets = {0, PADDING, 0, PADDING}; return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)]; } - (CGSize) intrinsicContentSize { CGSize intrinsicSuperViewContentSize = [super intrinsicContentSize] ; intrinsicSuperViewContentSize.width += PADDING * 2 ; return intrinsicSuperViewContentSize ; } @end
Hope this helps someone! Please note: if you want to fill in the top and bottom, you will need to change the following lines:
UIEdgeInsets insets = {0, PADDING, 0, PADDING};
For this:
UIEdgeInsets insets = {PADDING, PADDING, PADDING, PADDING};
And add this line under the same for width:
intrinsicSuperViewContentSize.height += PADDING * 2 ;
Ben Sep 14 '15 at 2:58 2015-09-14 14:58
source share