How to link multiple text views to a single text storage in TextKit 2

In TextKit 1 we have the method NSTextStorage.addLayoutManager(_:) that allows to show the same text in multiple text views. This method exists with NSLayoutManager but not with NsTextLayoutManager.

Is there a way to achieve the same thing with TextKit 2?

Answered by DTS Engineer in 793290022

I believe the following sample code has what you are looking for:

Specifically, please see toggleHidden() in TextAttachment.swift for how to change the text storage programmatically.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

Content manager allows to addition one or more layout managers.

let layoutManager = NSTextLayoutManager()
layoutManager.textContainer = textContainer

let contentManager = NSTextContentStorage()
contentManager.addTextLayoutManager(layoutManager)

that you can later assess via contentManager.textLayoutManagers. Additionally there is a flag automaticallySynchronizesTextLayoutManagers (defaults to true) to facilitate synchronization of multiple layout managers for that content manager.

Thanks! I have another question now: how can I link multiple NSTextContentStorage to the same NSTextStorage? The documentation for NSTextContentStorage reads:

By default, the framework initializes the NSTextContentStorage with NSTextStorage as the backing store.

But I don't see any way of accessing or setting the NSTextStorage. If I'm not supposed to do so, then how can I programmatically change the text?

I believe the following sample code has what you are looking for:

Specifically, please see toggleHidden() in TextAttachment.swift for how to change the text storage programmatically.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

Thanks. The part I was missing is the one the documentation for NSTextContentManager doesn't mention, which is that it is an abstract class whose (apparently) only concrete subclass is NSTextContentStorage, which has a textStorage property.

guard let textStorage: NSTextStorage = (textLayoutManager?.textContentManager as? NSTextContentStorage)?.textStorage else { return }

The sample code also changes the textStorage inside the block passed to textContentManager.performEditingTransaction(_:), which the documentation doesn't seem to explain why it's necessary.

How to link multiple text views to a single text storage in TextKit 2
 
 
Q