9

I'm trying to integrate the undo/redo features in a UITextView (I'm building a LateX editor) with no luck and to be honest I'm really confused about this argument. I don't understand the steps involved in those two operations, I mean I need two methods

  • one to remove the last inserted text
  • one to restore the text removed

One doubt is where I get the last inserted text? in other words where I have to register for the undo?

  • in textViewDidChange I can get the whole text
  • in textViewShouldChangeTextInRange I can get the last char inserted

I know that what I wrote wasn't the best explanation ever, But I hope someone here has faced the same problem in the past and can give me an hint. Basically ,to resume, I have to add the undo/redo features to a textview, possibly having two buttons linked with those actions.

Thanks in advance

Rui Peres
  • 25,741
  • 9
  • 87
  • 137
oiledCode
  • 8,589
  • 6
  • 43
  • 59

1 Answers1

24

I'm feeling like an idiot right now :( the solution was really really easy... The textView has already an undoManager so basically the steps to have undo/redo actions for a textView are : inside viewDidload :

myUndoManager = [textView undoManager];

where you want to perform the actions

[myUndoManager undo]; // or redo

I'm really dumb sometimes, I was almost writing my own undo code... I hope this can help someone

oiledCode
  • 8,589
  • 6
  • 43
  • 59
  • I tried using your code in your answer (I wish to do the same thing, have an undo and redo button), but it says that textView is undeclared. How did you declare it? –  Mar 04 '11 at 04:13
  • user: textView is "a text view". Any text view. You named it something, use that. – Kalle Jul 15 '11 at 10:16
  • 1
    So simple, and yet so many people are doing several pages long hacks to get around this. Would give +10 if I could. Thanks. – Kalle Jul 15 '11 at 10:29
  • I wish I could give you +100 if I could. I was just going to write my undo/redo code as well. Thanks so much! You are a hero :) – coolcool1994 Mar 17 '13 at 05:46
  • I am using UIDocument, which has its own undo manager, which is tracking various changes to the document. I am not sure why I would want another undo manager just for a textView. When someone pressed "undo", which manager am I going to ask? – Glyn Williams Oct 07 '14 at 12:22