Is it possible to use UILabel Inset?

I give the UILabel border to

Label.text = lbltext; Label.layer.borderColor = [[UIColor grayColor] CGColor]; Label.layer.borderWidth = 2; 

But there is no gap between the text and the border.
so how can i set the insert effect like UIButton in my label?

Thanks.

+6
iphone uilabel xcode4
source share
4 answers

Place the shortcut in the container view and apply a frame to the container.

+20
source share

You can subclass UILabel and override several methods:

The first gives you rounded corners and a border. You can customize border width, color, etc. As needed.

 - (void)drawRect:(CGRect)rect { self.layer.cornerRadius = 4.0; self.layer.borderWidth = 1; [super drawRect:rect]; } 

The second allows you to specify inserts to place the label text to the left of the left border.

 - (void) drawTextInRect:(CGRect)rect { UIEdgeInsets insets = {0,5,0,5}; [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)]; } 
+18
source share

Alternatively, without using a label, you can use the NSString method sizeWithFont:forWidth:lineBreakMode: which returns the size of the text. Then you can call the NSString drawInRect:withFont:lineBreakMode: , where your rect will be the one obtained from the sizeWithFont method, increased by the desired margin.

+1
source share

You can also add a space to the text for a very simple solution:

ObjC code (added by s1m0n as a comment)

 [label setText:[NSString stringWithFormat:@" %@ ", text]]; 

Monotouch Code (C #):

 Label.text = " "+lbltext; 

@Downvoting: If you vote, show at least some respect in explaining the reason, so we can all understand why this is a bad decision. Although this, of course, is not a general solution for all cases, in some cases it can be a very simple solution. Since the border is created inside the button, the text β€œattaches” to the border (or even overlaps), and adding a space can easily fix this.

+1
source share

All Articles