Is UILabel Inset effect Possible? [duplicate]

守給你的承諾、 提交于 2019-12-03 14:46:06

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

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)];
}
Maggie

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.

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.

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