Is UILabel Inset effect Possible? [duplicate]

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-01 05:19:13

问题


I am giving border to UILabel with

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

But There is no space between text and border.
so how can i set inset effect like UIButton in my Label?


回答1:


Put the label in a container view and apply the border to the container.




回答2:


You can subclass UILabel, and override a couple of methods:

The first gives you rounded corners and a border. You can tweak the border width, color etc. as needed.

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

    [super drawRect:rect];
}

The second lets you specify insets to position the label text away from the left border.

- (void) drawTextInRect:(CGRect)rect
{   
    UIEdgeInsets insets = {0,5,0,5};

    [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}



回答3:


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




回答4:


You can also add a space in the Text for a very simple solution:

ObjC code (added by s1m0n as comment)

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

Monotouch (C#) code:

Label.text = " "+lbltext;

@Downvoting: If you're down voting, show at least some respect by giving a reason so we can all learn why this is a bad solution. While it is certainly not a general solution for all cases, it might be a very simple solution in some cases. Because the border is created inside the Button, the text is "sticked" to the border (or there is even an overlap) and adding a space can easily fix this.



来源:https://stackoverflow.com/questions/6854991/is-uilabel-inset-effect-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!