我想在UILabel
文本中添加图像。但是我曾经在文本NSTextAttachment
末尾添加图像。UILabel
我将其子类化以使图像的大小适合我的文本。
现在我想在文本的开头再添加一张图片,我们可以说作为前缀UILabel
(请参阅所附图片)。
我试过了,但我没有找到任何好的解决方案。谁能帮我完成这件事。
我想在UILabel
文本中添加图像。但是我曾经在文本NSTextAttachment
末尾添加图像。UILabel
我将其子类化以使图像的大小适合我的文本。
现在我想在文本的开头再添加一张图片,我们可以说作为前缀UILabel
(请参阅所附图片)。
我试过了,但我没有找到任何好的解决方案。谁能帮我完成这件事。
附件是字符,您可以将其呈现为 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;
}
结果:
尝试这样的事情:
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];