所以我的问题是让我的 textView 能够撤消/重做操作(我使用两个按钮来执行此操作)。阅读文档我发现 UITextView 有一个内置的 undoManager 并且他的基本用法非常简单。到目前为止我做了什么?
我有一个包含 textView 的 viewController (EditorViewController)。
在 EditorViewcontroller.h
NSUndoManager *myUndoManager;
在 EditorViewController.m --> viewDidLoad
myUndoManager = [textView undoManager];
正如我所说的,两个按钮用于执行撤消/重做操作,这两个按钮位于 textView 的 inputAccessoryView 中,这个视图基本上是一个工具栏,有几个按钮用于将文本附加到 textView。
我有一个名为 appendText 的方法:
- (IBAction) appendText:(id)sender{
NSString *contentsToAdd;
NSMutableString *textViewContent;
NSRange cursorPosition;
if ([undoManager canUndo]) {
NSLog(@"yes canundo");
}
switch ([sender tag]) {
case 0:
[textView setScrollEnabled:NO];
contentsToAdd = @"[]";
cursorPosition = [textView selectedRange];
textViewContent = [[NSMutableString alloc]
initWithString:[textView text]];
[textViewContent insertString:contentsToAdd
atIndex:cursorPosition.location];
[textView setText:textViewContent];
[textViewContent release];
cursorPosition.location++;
textView.selectedRange=cursorPosition;
[textView becomeFirstResponder];
[textView setScrollEnabled:YES];
if (![undoManager canUndo]) {
NSLog(@" can't undo");
}
break;
// more case following 0..9
case 10:
[myUndoManager undo];
[break];
case 11 :
[myUndoManager redo];
break;
}
现在,如果我使用键盘书写,一切都很好,我的意思是撤消和重做可以正常工作。但是当我使用 appendText: 方法追加一些文本时,不会执行撤消和重做。如果我开始使用键盘再次写入撤消和重做(撤消堆栈的第一个元素是最后写入的文本)就像 if每次我附加一些文本时,撤消和重做堆栈都会被清除。我希望有人能给我一个提示..