如何在UIWebView中实现undo/redo

tha*_*rai 13 objective-c uiwebview rich-text-editor nsundomanager ios

我正在开发一个具有丰富文本编辑功能的应用程序.在ZSSRichTextEditor之上,我编写了我的编辑器代码.这里我的编辑器是UIWebView,它将通过javascript代码注入,以支持/编辑富文本内容.

ZSSRichTextEditor具有撤消/重做功能,但它不符合我的要求.所以我开始自己实现撤消/重做功能.

在我通过UndoManager之后,我开始知道实现undo/redo并不会让人头疼,因为Apple为我们提供了很多帮助.如果我们在适当的地方注册,那么UndoManager将处理所有其他事情.但在这里,我正在努力注册如何/在哪里注册UndoManger可编辑UIWebView.

有很多例子可以实现undo/redo,UITextView但是我找不到任何可编辑的东西UIWebView

请问有人可以指导我吗?

Ale*_*ren 0

首先,为历史记录创建两个属性,如下所示:

@property (nonatomic, strong) NSMutableArray *history;
@property (nonatomic) NSInteger currentIndex;
Run Code Online (Sandbox Code Playgroud)

然后我要做的是使用子类 ZSSRichTextEditor,以便在按下按键或完成操作时获得委托调用。然后在每次委托调用时,您可以使用:

- (void)delegateMethod {
    //get the current html
    NSString *html = [self.editor getHTML];
    //we've added to the history
    self.currentIndex++;
    //add the html to the history
    [self.history insertObject:html atIndex:currentIndex];
    //remove any of the redos because we've created a new branch from our history
    self.history = [NSMutableArray arrayWithArray:[self.history subarrayWithRange:NSMakeRange(0, self.currentIndex + 1)]];
}

- (void)redo {
   //can't redo if there are no newer operations
   if (self.currentIndex >= self.history.count)
       return;
   //move forward one
   self.currentIndex++;
   [self.editor setHTML:[self.history objectAtIndex:self.currentIndex]];
}

- (void)undo {
   //can't undo if at the beginning of history
   if (self.currentIndex <= 0)
       return;
   //go back one
   self.currentIndex--;
   [self.editor setHTML:[self.history objectAtIndex:self.currentIndex]];
}
Run Code Online (Sandbox Code Playgroud)

我还会使用某种 FIFO(先进先出)方法来保持历史记录的大小小于 20 或 30,这样内存中就不会出现这些疯狂的长字符串。但这取决于您根据内容在编辑器中的长度来决定。希望这一切都有道理。

  • 感谢您的回答!这肯定会起作用,但我相信应该有其他更好的方法来做到这一点。如果你看看像 Evernote、OneNote 这样的应用程序,他们处理得很好。我会再等几天才能得到适当的解决方案,否则我会采用这种方法:-) (2认同)