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

textContainerInset导致NSAttributedString背景色缩进错位问题求助

SwiftUI实时Markdown编辑器背景色缩进渗透问题求助

我正在开发一款SwiftUI实时Markdown编辑器,支持用户输入时实时格式化并隐藏语法。实现上采用NSTextView结合NSViewRepresentable,通过NSAttributedString条件设置文本属性实现了背景色高亮功能。但遇到一个问题:当文本缩进且换行时,背景色会随机渗入缩进区域,且问题位置会随窗口大小改变而变化。对比MacOS TextEdit的正确表现(缩进空白保持白色),排查发现是用于居中文本容器的textContainerInset代码导致该问题,注释掉该代码后问题消失,但无法实现容器居中,特此求助解决方法。

相关代码

// Observer for frame changes
NotificationCenter.default.addObserver(forName: NSView.frameDidChangeNotification, object: scrollView, queue: OperationQueue.main) { [weak textView] _ in
    guard let textView = textView else { return }
    print("Text View Frame: \(textView.frame)")
    print("Text Container Size: \(textView.textContainer?.containerSize ?? CGSize.zero)")
    if scrollView.frame.width < 750 {
        textView.textContainer?.containerSize = CGSize(width: scrollView.frame.width, height: CGFloat.greatestFiniteMagnitude)
        textView.textContainer?.widthTracksTextView = true
        //textView.textContainerInset = NSSize(width: (scrollView.frame.width - textView.frame.width) / 2, height: 0)
    } else {
        textView.textContainer?.containerSize = CGSize(width: 750, height: CGFloat.greatestFiniteMagnitude)
        textView.textContainer?.widthTracksTextView = false
        //textView.textContainerInset = NSSize(width: (scrollView.frame.width - 750) / 2, height: 0)
    }
}
textView.adjustFontSizeCallback = adjustFontSize
return scrollView

效果对比

  • 问题表现:文本缩进换行时,背景色渗入缩进空白区域,且位置随窗口大小变化
  • 正确效果(TextEdit):缩进空白区域保持白色,不受背景色影响

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 14:25:16