您好我使用以下代码为我的标签创建了一个底部边框
CALayer *border = [CALayer layer];
CGFloat borderWidth = 2;
border.borderColor = [UIColor darkGrayColor].CGColor;
border.frame = CGRectMake(0, _label.frame.size.height - borderWidth, _label.frame.size.width, _label.frame.size.height);
border.borderWidth = borderWidth;
[_label.layer addSublayer:border];
_label.layer.masksToBounds = YES;
但它的边界是标签的一半。我该如何解决呢?提前谢谢。
答案 0 :(得分:2)
你可以这样做:
使用CALayer
,您可以在UILabel
或任何其他UIControl
上创建边框。
1)底部边框
CALayer *bottomBorder = [CALayer layer];
bottomBorder.borderColor = [UIColor blackColor].CGColor;
bottomBorder.borderWidth = 1;
bottomBorder.frame = CGRectMake(0, CGRectGetHeight(myLabel.frame)-1, CGRectGetWidth(myLabel.frame), 1);
myLabel.clipsToBounds = YES;
[myLabel.layer addSublayer:bottomBorder];
2)顶部边框
CALayer *topBorder = [CALayer layer];
topBorder.borderColor = [UIColor blackColor].CGColor;
topBorder.borderWidth = 1;
topBorder.frame = CGRectMake(0, 0, CGRectGetWidth(myLabel.frame), 1);
myLabel.clipsToBounds = YES;
[myLabel.layer addSublayer:topBorder];
3)左边框
CALayer *leftBorder = [CALayer layer];
leftBorder.borderColor = [UIColor blackColor].CGColor;
leftBorder.borderWidth = 1;
leftBorder.frame = CGRectMake(0, 0, 1, CGRectGetHeight(myLabel.frame));
myLabel.clipsToBounds = YES;
[myLabel.layer addSublayer:leftBorder];
4)右边框
CALayer *rightBorder = [CALayer layer];
rightBorder.borderColor = [UIColor blackColor].CGColor;
rightBorder.borderWidth = 1;
rightBorder.frame = CGRectMake(CGRectGetWidth(myLabel.frame)-1, 0, 1, CGRectGetHeight(myLabel.frame));
myLabel.clipsToBounds = YES;
[myLabel.layer addSublayer:rightBorder];
答案 1 :(得分:1)
试试吧,
CALayer* layer = [lbl layer];
CALayer *bottomBorder = [CALayer layer];
bottomBorder.borderColor = [UIColor darkGrayColor].CGColor;
bottomBorder.borderWidth = 1;
bottomBorder.frame = CGRectMake(-1, layer.frame.size.height-1,layer.frame.size.width, 1);
[bottomBorder setBorderColor:[UIColor blackColor].CGColor];
[layer addSublayer:bottomBorder];
答案 2 :(得分:0)
您需要根据字符串以及所需的字体计算标签的宽度。 你可以得到像这样的大小
CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font
constrainedToSize:maximumLabelSize
lineBreakMode:yourLabel.lineBreakMode];
并在为边框设置框架时使用expectedLabelSize。
border.frame = CGRectMake(0, _label.frame.size.height - borderWidth, _expectedLabelSize.width , _label.frame.size.height);
希望它有所帮助。快乐编码!!
答案 3 :(得分:0)
请尝试使用以下代码。
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 50)];
[lbl setText:@" Testo di prova ..."];
[lbl setBackgroundColor:[UIColor clearColor]];
[[self view] addSubview:lbl];
[lbl sizeToFit];
CALayer * layer = [lbl layer];
CALayer * bottomBorder = [CALayer图层];
bottomBorder.borderColor = [UIColor darkGrayColor] .CGColor;
bottomBorder.borderWidth = 1;
bottomBorder.frame = CGRectMake(-1,layer.frame.size.height-1,layer.frame.size.width,1);
[bottomBorder setBorderColor:[UIColor blackColor] .CGColor];
[layer addSublayer:bottomBorder];