如何设置NSTextView的段落属性宽度

How to Set the Paragraph Property Width of NSTextView

我的英文很烂,不知道怎么形容。

请先看我上传的图片。这是尤利西斯的截图。

这应该是一个 NSTextView 控件。全选文本后,我发现它可以控制特定段落的左手偏移。

我试着模仿了一下

但是我发现NSMutable Paragraph Style好像达不到这样的效果,只能达到类似下图的效果

简单的说,我想实现上一张图的效果,但是只有第二张图的效果。

我看了另一个问题,主要是背景颜色的问题,想知道缩进的问题,这样可以达到更好的效果。

NSTextView selection highlights all characters even paragraph indents

Ulysses 是如何实现的?

您可以通过覆盖 NSLayoutManager 子类中的 fillBackgroundRectArray(_: count:forCharacterRange:color:) 来修改选择的绘图矩形。

class MyLayoutManager: NSLayoutManager {

    override func fillBackgroundRectArray(_ rectArray: UnsafePointer<NSRect>, count rectCount: Int, forCharacterRange charRange: NSRange, color: NSColor) {
        // selection rects to draw a highlight.
        var rects: [NSRect] = Array(UnsafeBufferPointer(start: rectArray, count: rectCount))

        // modify rects here...

        // call super and pass in your custom rects array.
        super.fillBackgroundRectArray(&rects, count: rectCount, forCharacterRange: charRange, color: color)
    }

}

你可以达到这样的效果:


顺便说一句,您可以使用以下方法替换文本视图的布局管理器:

textView.textContainer?.replaceLayoutManager(MyLayoutManager())