我附上标签的屏幕截图应显示以下内容。 时间戳文本由两个图像附加,另一个文本具有白色边框。 我通过使用NSTextAttachment将图像附加到标签,然后我附加必须在最后或两个图像之间显示的文本取决于条件。如果有一个标签我可以很容易地实现这一点,如果每次最后都有文字出现,但它不会看到这么多教程为标签的完整文本创建边框。有没有办法只为特定部分创建边框标签文字。
答案 0 :(得分:3)
您需要制作包含所需文字的图片并附加到文字NSTextAttachment
这里是
Objective-C版 您可以像这样制作PG图像
@implementation ImageHelper
+(UIImage*)imageForText:(NSString*)text{
UILabel * lblBadge = [[UILabel alloc] initWithFrame:CGRectMake(0,0,16,16)];
[lblBadge setTextAlignment:NSTextAlignmentCenter];
[lblBadge setLineBreakMode:NSLineBreakByClipping];
[lblBadge setTextColor:[UIColor darkGrayColor]];
[lblBadge.layer setCornerRadius:2.0f];
[lblBadge.layer setBorderWidth:1];
[lblBadge setText:text];
[lblBadge sizeToFit];
[lblBadge setBounds:CGRectMake(0,0,lblBadge.bounds.size.width + 4,lblBadge.bounds.size.height)];
UIGraphicsBeginImageContextWithOptions(lblBadge.bounds.size, NO, [UIScreen mainScreen].scale);
[lblBadge.layer setAllowsEdgeAntialiasing:YES];
[lblBadge.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
@end
使用示例
NSMutableAttributedString * normalNameString = [[NSMutableAttributedString alloc]initWithString:@"testing "];
NSTextAttachment * attachment = [[NSTextAttachment alloc] init];
attachment.image = [ImageHelper imageForText:@"PG-13"];
attachment.bounds = CGRectMake(0, -6, attachment.image.size.width, attachment.image.size.height);
[normalNameString appendAttributedString:[NSAttributedString attributedStringWithAttachment:attachment]];
self.lblText.attributedText = normalNameString;
Swift版本
您可以像这样制作PG图像
class imageHelper{
static func pgImage(textValue:String) ->UIImage{
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 15, height: 16))
label.lineBreakMode = .byClipping
label.textAlignment = .center
label.textColor = UIColor.darkGray
label.layer.borderColor = UIColor.darkGray.cgColor
label.layer.borderWidth = 1
label.layer.cornerRadius = 2
label.text = textValue
label.sizeToFit()
label.bounds = CGRect(x: 0, y: 0, width: label.bounds.size.width + 4, height: label.bounds.size.height)
UIGraphicsBeginImageContextWithOptions(label.bounds.size, false, UIScreen.main.scale)
label.layer.allowsEdgeAntialiasing = true
label.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
使用示例
let normalNameString = NSMutableAttributedString.init(string: "testing ")
let attachment = NSTextAttachment()
attachment.image = imageHelper.pgImage(textValue: "PG-13")
attachment.bounds = CGRect(x: 0, y: -6, width: (attachment.image?.size.width)!, height: (attachment.image?.size.height)!)
normalNameString.append(NSAttributedString(attachment: attachment))
self.lblText.attributedText = normalNameString
<强> RESULT 强>