这是为 UILabel 添加背景的代码,但它通过查看文本宽度超过标签宽度的点来检测换行符。
-(CAShapeLayer *)backgroundLayerForLabel:(UILabel *)label padding:(float)padding{
NSString * text = label.text;
NSArray * words = [text componentsSeparatedByString:@" "];
UILabel * sizeLabel = [UILabel new];
sizeLabel.frame = CGRectMake(0, 0, label.frame.size.width, 0);
sizeLabel.font = label.font;
[sizeLabel setText:@" "]; //just to get row height
float rowHeight = sizeLabel.intrinsicContentSize.height;
float runWidth = 0.0f;
float maxWidth = ceilf(label.frame.size.width);
float startingX = label.frame.origin.x - padding;
UIBezierPath * path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(startingX, label.frame.origin.y)];
for (NSString * word in words){
[sizeLabel setText:[NSString stringWithFormat:@"%@", word]];
float sizeWidth = sizeLabel.intrinsicContentSize.width;
[sizeLabel setText:[NSString stringWithFormat:@"%@ ", word]];
float sizeSpaceWidth = sizeLabel.intrinsicContentSize.width;
float nextWidth = floorf(sizeWidth + runWidth);
if (nextWidth > maxWidth){ //spans next line
[path addLineToPoint:CGPointMake(startingX + runWidth + padding, path.currentPoint.y)];
[path addLineToPoint:CGPointMake(path.currentPoint.x, path.currentPoint.y + rowHeight)];
runWidth = sizeSpaceWidth;
} else {
runWidth += sizeSpaceWidth;
}
}
[path addLineToPoint:CGPointMake(startingX + runWidth + padding, path.currentPoint.y)];
[path addLineToPoint:CGPointMake(path.currentPoint.x, path.currentPoint.y + rowHeight)];
[path addLineToPoint:CGPointMake(startingX, path.currentPoint.y)];
[path closePath];
CAShapeLayer * layer = [CAShapeLayer layer];
layer.path = path.CGPath;
layer.fillColor = [UIColor whiteColor].CGColor;
return layer;
}
nextWidth > maxWidth,这就是你的换行符开始的地方,runWidth 变量是句子的长度。像这样使用:
UILabel * label = [UILabel new];
label.frame = CGRectMake(20, localY, labelWidth, 0);
label.font = [UIFont systemFontOfSize:24.0f weight:UIFontWeightSemibold];
label.textColor = [UIColor blackColor];
label.text = @"This is a really long quotes. I know. a. b. c. defghi. jklmn. op. q. r. stuv. ";
label.numberOfLines = 4;
label.lineBreakMode = NSLineBreakByWordWrapping;
[label sizeToFit];
CAShapeLayer * layer = [self backgroundLayerForLabel:label padding:5.0f];
layer.shadowColor = [UIColor blackColor].CGColor;
layer.shadowOffset = CGSizeMake(0, 1);
layer.shadowRadius = 2.0f;
layer.shadowOpacity = 0.8f;
[cell.layer addSublayer:layer];
[cell addSubview:label];
给你这样的东西: