0

I have an NSTextView that I bind to a String. The NSTextView has isRichText set to false. The text is editable by the user.

I want to update the font and line-hieght dynamically. Setting the font with textView.font works at any time.

I only seem to be able to set the paragraph style, for the line-height before the binding is in place. After that the same code has no effect on the text layout.

I am using the following code:

let paragraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.lineHeightMultiple = style.lineHeightMultiple
editableText.defaultParagraphStyle = paragraphStyle

Can anybody help me with what I am doing wrong? Thank you.

Giles
  • 1,428
  • 11
  • 21
  • `defaultParagraphStyle` is used when there is no text in the text view and the user starts typing. Change the paragraph style of the text in the text view or of the attributed string used in the binding. – Willeke Nov 05 '18 at 16:19
  • Thank you @Willeke. I am not using an attributed string, I am binding to a simple String. Do I still have to update things through textStorage? – Giles Nov 05 '18 at 16:29

1 Answers1

1

With thanks to @Willeke, and this question, I have a solution to this. As suggested, I have had to go to the text storage for this, and set attributes over the full text range. This does feel wrong though, because I am setting the NSTextView as plain-text and therefore I consider a style to be applied wholesale.

If setting attributes as below, the textView.font setting is dropped, so all attributes must be applied in the same way.

let paragraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.lineHeightMultiple = style.lineHeightMultiple

let storageRange = NSMakeRange(0, editableText.textStorage!.string.count)
editableText.textStorage!.setAttributes(
            [NSAttributedStringKey.paragraphStyle : paragraphStyle,
             NSAttributedStringKey.font : style.noteFont],
            range: storageRange)
Giles
  • 1,428
  • 11
  • 21