Center NSTextAttachment image next to single line UILabel

后端 未结 10 1136
太阳男子
太阳男子 2020-11-30 16:51

I\'d like to append an NSTextAttachment image to my attributed string and have it centered vertically.

I\'ve used the following code to create my string

10条回答
  •  时光说笑
    2020-11-30 17:20

    You can change the rect by subclassing NSTextAttachment and overriding attachmentBoundsForTextContainer:proposedLineFragment:glyphPosition:characterIndex:. Example:

    - (CGRect)attachmentBoundsForTextContainer:(NSTextContainer *)textContainer proposedLineFragment:(CGRect)lineFrag glyphPosition:(CGPoint)position characterIndex:(NSUInteger)charIndex {
        CGRect bounds;
        bounds.origin = CGPointMake(0, -5);
        bounds.size = self.image.size;
        return bounds;
    }
    

    It's not a perfect solution. You have to figure out the Y-origin “by eye” and if you change the font or the icon size, you'll probably want to change the Y-origin. But I couldn't find a better way, except by putting the icon in a separate image view (which has its own disadvantages).

提交回复
热议问题