Learn Courses My Dashboard

How to use NSTextAttachment in iOS15 (obj-c)

I am using NSTextAttachment to add a small image to the beginning of the attributedText of my label (with max number of lines == 2).

NSTextAttachment *iconAttachment = [NSTextAttachment new];
iconAttachment.bounds = CGRectMake(0, (*myFontHeight* - 13) / 2, 13, 13); 
iconAttachment.image = image;
NSAttributedString *iconAttributedString = [NSAttributedString attributedStringWithAttachment:iconAttachment];
NSMutableAttributedString *finalString = [[NSMutableAttributedString alloc] initWithAttributedString:self.myString];
[finalString insertAttributedString:[[NSAttributedString new] initWithString:@" "] atIndex:0];
[finalString insertAttributedString:iconAttributedString atIndex:0];

myLabel.attributedString = finalString;

Works well on iOS14 or less, but on iOS15+, if text should take 2 lines of the label - it only takes 1 now and do it incorrectly - its placed in the vertical center of the label, which height was already calculated for 2 lines before.

Apple documentation says

In macOS 12 and iOS 15 and later, NSTextAttachmentViewProvider and NSTextAttachmentLayout provide additional capabilities to represent document locations in terms of an NSTextLocation or an NSTextRange, and provide support for view-based text attachments.

But I still can’t understand, what is the best way to solve such a small problem (using NSTextAttachmentViewProvide and NSTextAttachmentLayout looks too difficult for that).