Reputation: 1490
I wanted to add image in UILabel
along with text. However I used NSTextAttachment
to add image at the end of UILabel
text. I have subclass it to to fit the size of image to my text.
Now I want to add one more image in the beginning of the text, we can say as a prefix of UILabel
(Please see the image attached).
I tried it but I do not found any good solution. can anybody please help me to get this done.
Upvotes: 0
Views: 1527
Reputation: 5076
Attachment it is character, you can present it as AttributedString and use it for replace some character in the string. You can add space as first character and use replaceCharactersInRange: method to replace the character to attachment:
<...>
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;
}
Result:
Upvotes: 2
Reputation: 4246
I see you are using a UITableView
. For the prefix ImageView, why not use the property of the UITableViewCell
, imageView
?
That will simplify your solution hopefully.
Upvotes: 0
Reputation: 587
try somethik like this:
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];
Upvotes: 0