7

How can I set an NSTextView to an NSAttributedString? I do not want to use a textConainer, and I tried:

[myTextView insertText:myMutableAttributedString];

but it didn't work. Nothing happened...not even a warning or a runtime error. Any help would be appreciated.

user657819
  • 141
  • 1
  • 4

4 Answers4

14

Textview must be editable to insert.

[myTextView setEditable:YES];
[myTextView insertText:myMutableAttributedString];
[myTextView setEditable:NO];
estobbart
  • 1,137
  • 12
  • 28
  • 'insertText:' is deprecated: first deprecated in macOS 10.11 - Use -insertText:replacementRange: from NSTextInputClient instead. Since the method is designed to be used solely by the input system, the message should never be sent to a text view from applications. Any content modifications should be via either NSTextStorage or NSText methods. – Mark Bridges Dec 12 '17 at 16:03
4

In Swift 2.2:

myTextView.textStorage?.setAttributedString(myMutableAttributedString)

In Objective-C:

[[myTextView textStorage] setAttributedString:myMutableAttributedString];

M. Mayer
  • 133
  • 1
  • 7
3

You should call -setString with an empty string before calling that method (otherwise you're inserting text into a null string object):

[myTextView setString:@""];
[myTextView insertText:myMutableAttributedString];
indragie
  • 18,002
  • 16
  • 95
  • 164
-2

the textView is createed programmatically? if you load the NSTextView from xib,it will bi fine.

Jabber
  • 1
  • 4