How to undo with NSTextview

I want to implement undo after replacing part of the text in NSTextView. I am replacing part of the text with the following code

- (void)omeAction
{
    NSString *fullString = [self.textView string];
    NSRange selectedRange = [self.textView selectedRange];
    NSString *selectedString = [fullString substringWithRange:selectedRange];

    NSString *stringToReplace = ...;
    [[self.textView textStorage] beginEditing];
    [[self.textView  textStorage] replaceCharactersInRange:selectedRange withString:stringToReplace];
    [[self.textView textStorage] endEditing];
}

      

While doing undo, I could not undo the text replacement

+3


source to share


2 answers


From Cocoa Text Architecture Guide: Text Editing - Text Change Notifications and Delegate Messages :

When making changes to the text, you must make sure that the changes have been correctly made and recorded in different parts of the text system. You do this by copying each batch of potential changes with messages shouldChangeTextInRange: replacementString: and didChangeText. These methods ensure that appropriate messages are sent to delegates and notifications are sent ...

In my experience, this includes creating an appropriate undo operation.



So, you would do:

if ([self.textView shouldChangeTextInRange:selectedRange replacementString:stringToReplace])
{
    [[self.textView textStorage] beginEditing];
    [[self.textView textStorage] replaceCharactersInRange:selectedRange withString:stringToReplace];
    [[self.textView textStorage] endEditing];
    [self.textView didChangeText];
}

      

+6


source


I first tried to solve undo and shouldChangeTextInRange: replacementString: did the trick. However, I found that insertText: replacementRange: had the same effect.

[self insertText:attributedString replacementRange:range];

      



Or:

if ([textView shouldChangeTextInRange:range replacementString:string]) { //string
  [textStorage beginEditing];
  [textStorage replaceCharactersInRange:range withAttributedString:attributedString];
  [textStorage endEditing];
  [textView didChangeText];
}

      

0


source







All Articles