ios - UIWebView中如何实现undo/redo

标签 ios objective-c uiwebview rich-text-editor nsundomanager

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

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

在我完成UndoManager之后我开始知道实现撤消/重做不会那么令人头疼,因为 Apple 为我们提供了很多帮助。如果我们在适当的地方注册它,那么 UndoManager 将处理所有其他事情。但是在这里,我正在努力如何/在哪里为可编辑的 UIWebView 注册 UndoManger

UITextView 中有很多实现撤消/重做的例子,但我没有找到任何可编辑的 UIWebView

有人可以指导我吗?

最佳答案

首先,像这样为历史创建两个属性:

@property (nonatomic, strong) NSMutableArray *history;
@property (nonatomic) NSInteger currentIndex;

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

- (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]];
}

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

关于ios - UIWebView中如何实现undo/redo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30498987/

相关文章:

ios - UIBezierPath:在 iPad 上创建的控制点多于 iPhone?

html - iOS UIWebView 为 html 页面设置语言

ios - 如何查询 Parse 以从自定义类获取信息并将其显示在 Swift 的文本字段中?

ios - 在 iOS 应用程序中测试 Cognito 身份验证

ios - 在 NSUserDefaults 中保存继承的对象

iphone - 使用 loadHTMLString 在 drawRect 中渲染 UIWebView

ios - 具有复杂格式的 UITableViewCell 的最佳方法

ios - 等待要在下一次分派(dispatch)时执行的 block 如何成功?

ios - AirPlay 镜像的欠扫描问题

objective-c - 从 View Controller 传递后,传递的托管对象上下文为空