Search code examples
iosobjective-cnsattributedstringnstextattachment

How can I Add second NSTextAttachement image in uilabel?


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.

enter image description here


Solution

  • 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:

    enter image description here