mahan
mahan

Reputation: 15015

Restrict size of NSTextAttachment image

I am trying to insert an image in UITextView. I have used the following code.

extension TextView {
    func add(image: UIImage) {
        let attachment = NSTextAttachment()
        attachment.image = image

        attachment.bounds = CGRect(x: 0, y: 0, width: 40, height: 40)

        let attString = NSAttributedString(attachment: attachment)

        self.attributedText = attString
    }
}

The parent UIViewController calls add(image: UIImage).

In func textViewDidChange(_ textView: UITextView), I save the attributedText in CoreData as a Transforable NSAttributedString. I use NSAttributedStringTransformer for Transformer

enter image description here

The image's size is 40X40 when added. The image has also the same size when I dismiss the parent UIViewController and present it back. However, if I quit the app and relaunch it, the image is not 40X40. It is larger than then UIScreen's size.

How to set size of the image to be 40X40 even after quitting the app?

Upvotes: 0

Views: 378

Answers (2)

Adrián Castro
Adrián Castro

Reputation: 1

The problem is that bounds of NSTextAttachment are lost after you persist data in core data. I have same situation with same configuration as you. You can save bounds of image separately and apply them in transformation as this code do:

attributedString.enumerateAttribute(.attachment, in: NSRange(location: 0, length: attributedString.length), options: []) { value, range, stop in
            if let value = value as? NSTextAttachment {
                let scale =  value.bounds.size.width
                let newRect = CGRect(x: value.bounds.origin.x, y: value.bounds.origin.y, width: widthboundsSaved, height: heightboundsSaved)
                value.bounds = newRect
            }
        }

This has one problem: if you have more than 1 image in same attributedText, you will have to save and recover bounds too. I didn't find any other solution. Don't know why coredata lost bounds.

Upvotes: 0

Léo Natan
Léo Natan

Reputation: 57060

By setting attachment bounds, you are not resizing the actual image, just the display bounds. Looks like the attributed string transformer doesn’t serialize the bounds you set. You will have to either resize the image directly, or extend the transformer to add the bounds after deserializing from data.

Edit: I see that NSAttributedStringTransformer is not an Apple-provided transformer. So take a look at the source code and see why the bounds are not serialized properly.

Upvotes: 1

Related Questions