cocoanstextviewnsparagraphstyle

How to Set the Paragraph Property Width of NSTextView


My English is terrible, and I don't know how to describe it.

Please look at the picture I uploaded first. This is a screenshot from Ulysses.

enter image description here

This should be a NSTextView control. After selecting all the text, I found that it could control the left-hand offset of a particular paragraph.

I tried to imitate it.

But I found that NSMutable Paragraph Style does not seem to achieve such an effect, it can only achieve the effect similar to that of the following picture.

enter image description here

Simply put, I want to achieve the effect of the previous picture, but only the effect of the second picture.

I looked at another question, but it was mainly about background color, and I wanted to know the question of indentation so that I could achieve more results.

NSTextView selection highlights all characters even paragraph indents

How is Ulysses implemented?


Solution

  • You can modify drawing rectangles of selection by overriding fillBackgroundRectArray(_: count:forCharacterRange:color:) in your NSLayoutManager subclass.

    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)
        }
    
    }
    

    And you can achieve something like this:

    enter image description here


    BTW, you can replace text view's layout manager by using:

    textView.textContainer?.replaceLayoutManager(MyLayoutManager())