You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TextKit 2中将多个文本视图关联到单个文本存储?

在TextKit 2中实现同一文本多视图显示

可以实现,TextKit 2的架构与TextKit 1不同,需要通过NSTextContentManager作为中间层来共享文本内容,具体步骤如下:

  • 创建一个共享的NSTextStorage实例,作为统一的文本数据源
  • 初始化NSTextContentManager实例,并将其textStorage属性绑定到上述共享的NSTextStorage
  • 为每个需要显示同一文本的文本视图,获取其NSTextLayoutManager,并将该布局管理器的textContentManager设置为共享的NSTextContentManager

示例代码:

// 创建共享文本存储
let sharedTextStorage = NSTextStorage(string: "这是需要在多视图共享的文本内容")

// 初始化共享内容管理器并绑定文本存储
let sharedContentManager = NSTextContentManager()
sharedContentManager.textStorage = sharedTextStorage

// 为第一个文本视图配置共享内容管理器
let textView1 = NSTextView()
textView1.textLayoutManager?.textContentManager = sharedContentManager

// 为第二个文本视图配置共享内容管理器
let textView2 = NSTextView()
textView2.textLayoutManager?.textContentManager = sharedContentManager

完成上述配置后,多个文本视图会同步显示同一文本内容,任何一方对文本的修改都会实时同步到其他视图。

内容的提问来源于stack exchange,提问作者Nickkk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 06:22:03