0

我想在UILabel文本中添加图像。但是我曾经在文本NSTextAttachment末尾添加图像。UILabel我将其子类化以使图像的大小适合我的文本。

现在我想在文本的开头再添加一张图片,我们可以说作为前缀UILabel(请参阅所附图片)。

我试过了,但我没有找到任何好的解决方案。谁能帮我完成这件事。

在此处输入图像描述

4

3 回答 3

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

结果:

在此处输入图像描述

于 2015-08-07T09:20:35.653 回答
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];
于 2015-08-07T08:26:01.120 回答
0

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

希望这将简化您的解决方案。

参考

于 2015-08-07T08:33:29.470 回答