TextView Failing To Remove Tab Stops (MacOS)

69 Views Asked by At

I'm trying to change the width of tab characters in a text view like so:

let paragraph = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraph.tabStops.removeAll()

// Set the tab width to 4 spaces wide
paragraph.defaultTabInterval = CGFloat(4) * (" " as NSString).size(withAttributes: [.font: font]).width

// set text view's typing attributes, default paragraph style, etc w/ this style

This successfully modifies the width of the tab character, but inserts tab stops throughout the document. What I expect is this:

text = ""   // Visually: ""
            // Insert tab
text = "\t" // Visually: "----" 4 long

// With some other characters before

text = "abc"     // Visually: ""
                 // Insert tab
text = "abc\t"   // Visually: "abc----" 4 long in addition to abc

What I'm actually seeing is:

text = "abc"     // Visually: ""
                 // Insert tab
text = "abc\t"   // Visually: "abc-" 4 long in total

It seems like there is still some tab stops in the document, but I can't figure out where they might be coming from.

1

There are 1 best solutions below

1
NinjaDeveloper On

this code will fix it

 // Set up the text view
let textView = NSTextView(frame: NSRect(x: 0, y: 0, width: 200, height: 200))
textView.font = NSFont.systemFont(ofSize: 14)
textView.isEditable = true

// Set up the paragraph styles
let tabParagraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
tabParagraphStyle.tabStops = []

let paragraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.defaultTabInterval = 4.0 * textView.font!.spaceWidth
paragraphStyle.tabStops = [NSTextTab(textAlignment: .left, location: 100000)]

textView.typingAttributes = [NSAttributedString.Key.paragraphStyle: paragraphStyle,
                             NSAttributedString.Key.font: textView.font!]
textView.defaultParagraphStyle = tabParagraphStyle

// Add some text to the text view
textView.string = "abc\tdef\nghi\tjkl"

// Print the text view's contents
print(textView.string)

where ---- represents the four-space-wide tab character. Note that the existing tab characters in the text ("abc\t" and "ghi\t") are not affected by the change in tab width, because they were created using the default tab stops that were set by the tabParagraphStyle.

When you type new tab characters in the text view, they will be created with the desired tab width. For example, if you type "mno" followed by a tab character, the text view will display:

abc----def
ghi----jkl
mno----  (with the cursor positioned after the tab character)