views:

48

answers:

1

I've got an attributed string bound to a NSTextView. I'm using a method that is called (using KVO) every time the string is edited to add background color attributes to string based on a regEx match. I do this by creating a new mutable attributed string with -initWithAttributedString: then -beginEditing, -addAttribute:, -endEditing. Once I've added all the background color attributes I want, I call the string's setter [self setTextViewString:mutableAttributedString] The issue is, that if there actually are any attributes added to the string, it kills undo and moves the cursor to the end of the string.

How can I maintain undo? I've maintained cursor position by calling the textView's selectedRanges and setSelectedRanges: methods on either side of the setter, but this still seems a bit hackish.

I wasn't able to bind the textview directly to the mutableattributedstring, but it seems like there should be a more direct way to modify the bound string so it doesn't mess up editing.

PS, the addition of attributes happens after the KVO method finishes by calling -performSelectorOnMainThread: It was the only way I could get the added attributes to display.

A: 

[self setTextView:mutableAttributedString]

Pardon? You're setting your textView to an attributed string? Wouldn't it make more sense to keep your text view there?

Try getting the text view's textStorage and replacing its contents with the new attributed string by sending the text storage a setAttributedString: message.

Peter Hosey
Sorry, that was unclear and I changed it to make more sense. I have my textview bound to an attributed string so I am calling the *string's* setter, not a setter for the textview itself.
MacRae Linton