如何在 uilabel 中添加第二个 NSTextAttachment 图像?

How can I Add second NSTextAttachement image in uilabel?

我想在 UILabel 中添加图片和文字。但是我使用 NSTextAttachmentUILabel 文本的末尾添加图像。我将其子类化为使图像大小适合我的文本。

现在我想在正文的开头再添加一张图片,我们可以说是UILabel的前缀(请看附件)。

我试过了,但没有找到好的解决办法。谁能帮我完成这件事。

试试这样的方法:

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 20)];
UIImageView *imgViewPrefix = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"feedbackLocItemActiveIco"]];
imgViewPrefix.frame = CGRectMake(0, 0, 20, 20);

UIImageView *imgViewPostfix = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"feedbackLocItemActiveIco"]];
imgViewPostfix.frame = CGRectMake(80, 0, 20, 20);

label.text = @"    my text";
label.textColor = [UIColor whiteColor];
[label addSubview:imgViewPrefix];
[label addSubview:imgViewPostfix];

我看到您正在使用 UITableView。对于前缀ImageView,为什么不用UITableViewCellimageView的属性?

这有望简化您的解决方案。

Reference

附件是字符,您可以将其呈现为AttributedString,并用它来替换字符串中的某些字符。 您可以添加 space 作为第一个字符并使用 replaceCharactersInRange: 方法将字符替换为附件:

<...>
NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] initWithString:@" with attachments " attributes:[self attributesWithAttachment:nil]];

[attrString replaceCharactersInRange:NSMakeRange(0, 1) withAttributedString:[self attachmentWithImage:[UIImage imageNamed:@"1.png"]]];
[attrString replaceCharactersInRange:NSMakeRange(5, 1) withAttributedString:[self attachmentWithImage:[UIImage imageNamed:@"2.png"]]];
[attrString replaceCharactersInRange:NSMakeRange([attrString length] - 1, 0) withAttributedString:[self attachmentWithImage:[UIImage imageNamed:@"3.png"]]];

self.label.attributedText = attrString;
<...>

- (NSAttributedString*)attachmentWithImage:(UIImage*)attachment
{
NSTextAttachment* textAttachment = [[NSTextAttachment alloc] initWithData:nil ofType:nil];
textAttachment.image = attachment;

NSAttributedString* string = [NSAttributedString attributedStringWithAttachment:textAttachment];

return string;
}

结果: