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

时间:2015-08-07 07:56:23

标签: ios objective-c nsattributedstring nstextattachment

我想在UILabel中添加图片以及文字。但是,我使用NSTextAttachmentUILabel文本末尾添加了图片。我已经将它子类化为适合我的文本的图像大小。

现在我想在文本的开头添加一个图像,我们可以说是UILabel的前缀(请参阅附图所示)。

我尝试了但是我没有找到任何好的解决方案。任何人都可以帮我完成这件事。

enter image description here

3 个答案:

答案 0 :(得分:2)

附件是字符,您可以将其呈现为AttributedString并使用它来替换字符串中的某些字符。 您可以添加空格作为第一个字符,并使用 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;
}

结果:

enter image description here

答案 1 :(得分:0)

尝试像这样的事情:

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];

答案 2 :(得分:0)

我发现您使用的是UITableView。对于前缀ImageView,为什么不使用UITableViewCellimageView

的属性

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

Reference