iphone - 使用 UITextView 撤消/重做 (iOS/iPHone)

标签 iphone uitextview undo nsundomanager redo

我有一个 View ,其中 UITextView 始终具有焦点。我想要做的是扩展内置撤消/重做行为,以支持当我以编程方式设置文本时(例如,当我清除它时,通过将其设置为 @"")的撤消/重做。

由于只有firstResponder 获取撤消/重做事件,我想我只需使用UITextView 的undoManager 属性来创建我的调用。例如,

// Before clearing the text...
[[self.myTextView.undoManager prepareWithInvocationTarget:self] undoClear:self.myTextView.text]; 
[self.myTextView.undoManager setActionName:@"Clear"];

// ...

-(void)undoClear:(NSString *)textToRestore
{
    self.myTextView.text = textToRestore;
    if ([self.myTextView.undoManager isUndoing])
    {
      // Prepare the redo.
      [[self.myTextView.undoManager prepareWithInvocationTarget:self] undoClear:@""];  
    }
}

不幸的是,这不起作用。它:

  1. 将一个空项目引入撤消堆栈(“撤消”)
  2. “撤消清除”会添加到该项目之后(如果我点击“撤消”,我会看到“撤消清除”)
  3. 但是,“撤消清除”和“重做清除”可以正常工作,然后我会再次看到“撤消清除”,并且此后就不再起作用。

有什么想法吗?我这样做是错误的吗?

更新:似乎我已经解决了空撤消项问题:当我在调用prepareWithInitationTarget之后设置UITextView的文本时,就会发生这种情况。如果我之前调用它,它就不会发生。有趣的是,如果我不调用prepareWithInitationTarget(即通常情况下,当我设置 UITextView 的文本时),则空项目不会被推送到撤消堆栈上。

最佳答案

好的,明白了:

#1 的问题如我原始帖子的更新中所述。

问题 #2 和问题 #3 只是我错误地使用了 NSUndoManager。我最终的 unClear 方法(在撤消时调用该方法如下:

-(void)undoClear:(NSString *)textToRestore
{   
    NSString *textBackup = [self.myTextView.text copy];

    self.myTextView.text = textToRestore;

    if ([self.myTextView.undoManager isUndoing])
    {
        // Prepare the redo.
        [[self.myTextView.undoManager prepareWithInvocationTarget:self] undoClear:@""];     
    }
    else if ([self.myTextView.undoManager isRedoing])
    {
        [[self.myTextView.undoManager prepareWithInvocationTarget:self] undoClear:textBackup];
    }

    [textBackup release];
}

它现在正在正常工作。

关于iphone - 使用 UITextView 撤消/重做 (iOS/iPHone),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4070291/

相关文章:

ios - 怎么设置game over在游戏结束的时候和开始的条件一样?

iphone - 如何在导航栏中添加多个控件?

iPhone iOS5 有哪些选项可以播放我未捆绑的音频?

iphone - UITextInput setMarkedText :selectedRange not working?(不可能!)

swift - 我如何将文本从文本字段附加到 TextView 并每次快速换行?

git - 撤消 git merge ,保留后来的提交

java - Java 中的撤消和重做操作事件

ios - 与 iOS 分发系统混淆

c# - ASP.net Web App 撤消支持

ios - 如何绘制末尾有段落截断的非矩形 UILabel?