Convenient NSTextAttachment image resizing

Today i was faced with the task of building a dynamic NSAttributedString consiting of arbitrary text and icons. Obviously all the icons had to match the text size.

Starting point
Screen Shot 2016-02-19 at 16.58.23

This can be accomplished by just setting the bounds of the NSTextAttachment like so:

textAttachment.bounds = CGRectMake(0, 0, 16, 16)

Sure, that works but it’s not a very elegant solution. It also ignores the aspect ratio of the image.

So instead i decided to dive into Swift extensions and added the following function to NSTextAttachment:

extension NSTextAttachment {
    func setImageHeight(height: CGFloat) {
        guard let image = image else { return }
        let ratio = image.size.width / image.size.height
        bounds = CGRectMake(bounds.origin.x, bounds.origin.y, ratio * height, height)

Now it’s simply a matter of calling the function to resize your NSTextAttachment images and keep the aspect ratio!


Here is the result
Screen Shot 2016-02-19 at 17.00.27

Looks much better, no?

Leave a Reply

Your email address will not be published. Required fields are marked *