NSTextAttachment lagging in textkit 2

I have an attributedString with 100 NSTextAttachments(contains image of 400kb). When i scroll the textview, it is lagging, When i did the same in textkit 1, it is butter smooth. It can be because of how textkit 1 & 2 layout the elements.

        let attachment = NSTextAttachment()
        attachment.image = UIImage(named: "image2")
        
        let attachmentString = NSAttributedString(attachment: attachment)
        let mutableAttributedString = NSMutableAttributedString(attributedString: textView.attributedText)

        for _ in 0...100 {
            mutableAttributedString.append(NSAttributedString(string: "\n"))
            mutableAttributedString.append(attachmentString)
            
        }

        textView.attributedText = mutableAttributedString

How to handle images in textkit 2 so that it feels smooth while scrolling textview?

Is the issue still there after the initial scrolling? Concretely, if you scroll incrementally down to the end, which makes sure that all the text is laid out, Does the issue still happen?

TextKit2 lays out text lazily, meaning that text is only laid out when it is about to be presented. That helps achieve better performance in many cases, such as initial loading and jumping to a certain page.

In your case though, loading and laying out the image attachments may be a bit heavy, and so I am guessing that doing that on the fly while scrolling may indeed become an issue. If that is the case, you can try NSTextLayoutManager.ensureLayout(for:) to lay out the text range beforehand.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

NSTextAttachment lagging in textkit 2
 
 
Q