Ios 为什么不显示NSAttributedString的UILabel?

Ios 为什么不显示NSAttributedString的UILabel?,ios,uitextview,nsattributedstring,Ios,Uitextview,Nsattributedstring,我正在尝试为图表创建一个键,我需要一个字符串,后跟一个彩色框,然后是另一个字符串。但是,尝试此操作时,文本不会显示。我以前没有使用过属性字符串,所以这可能是显而易见的。谢谢 UILabel *titleLabel = (UILabel*) [cell viewWithTag:101]; UIView *myBox = [[UIView alloc] initWithFrame:CGRectMake(1, 1, 30, 30)]; myBox.backgroundColor = [UIColor

我正在尝试为图表创建一个键,我需要一个字符串,后跟一个彩色框,然后是另一个字符串。但是,尝试此操作时,文本不会显示。我以前没有使用过属性字符串,所以这可能是显而易见的。谢谢

UILabel *titleLabel = (UILabel*) [cell viewWithTag:101];
UIView *myBox  = [[UIView alloc] initWithFrame:CGRectMake(1, 1, 30, 30)];
myBox.backgroundColor = [UIColor blueColor];

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"test string"];
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = [self imageWithView:myBox];

CGFloat oldWidth = textAttachment.image.size.width;

CGFloat scaleFactor = oldWidth / (titleLabel.frame.size.width - 10);
textAttachment.image = [UIImage imageWithCGImage:textAttachment.image.CGImage scale:scaleFactor orientation:UIImageOrientationUp];
NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:textAttachment];
[attributedString replaceCharactersInRange:NSMakeRange(6, 1) withAttributedString:attrStringWithImage];
titleLabel.attributedText = attributedString;

作为一项完整性检查,如果您将标签设置为纯文本,标签是否会显示?当我将其设置为纯文本时,它在设置属性文本之前工作。在构建视图时,您正在自己的视图上调用
imageWithView
。我不确定你到底期望发生什么。或者,
imageWithView
只是返回一个矩形图像?我只是想用它创建一个矩形图像。作为一个合理性检查,如果你用纯文本设置标签,它会出现吗?它在设置属性文本之前工作,当我将它设置为纯文本时。在构建视图时,您正在自己的视图上调用
imageWithView
。我不确定你到底期望发生什么。或者
imageWithView
只是返回一个矩形图像吗?我只是想用它创建一个矩形图像。