objective-c - 如何使用 NSTextview 实现撤销

标签 objective-c macos nstextview undo-redo

我想在替换 NSTextView 中的部分文本后执行撤消操作。我正在用以下代码替换部分文本

- (void)omeAction
{
    NSString *fullString = [self.textView string];
    NSRange selectedRange = [self.textView selectedRange];
    NSString *selectedString = [fullString substringWithRange:selectedRange];

    NSString *stringToReplace = ...;
    [[self.textView textStorage] beginEditing];
    [[self.textView  textStorage] replaceCharactersInRange:selectedRange withString:stringToReplace];
    [[self.textView textStorage] endEditing];
}

在执行撤消时我无法真正撤消文本替换

最佳答案

来自 Cocoa Text Architecture Guide: Text Editing – Text Change Notifications and Delegate Messages :

In actually making changes to the text, you must ensure that the changes are properly performed and recorded by different parts of the text system. You do this by bracketing each batch of potential changes with shouldChangeTextInRange:replacementString: and didChangeText messages. These methods ensure that the appropriate delegate messages are sent and notifications posted. …

根据我的经验,这包括生成相关的撤消操作。

所以,你会这样做:

if ([self.textView shouldChangeTextInRange:selectedRange replacementString:stringToReplace])
{
    [[self.textView textStorage] beginEditing];
    [[self.textView textStorage] replaceCharactersInRange:selectedRange withString:stringToReplace];
    [[self.textView textStorage] endEditing];
    [self.textView didChangeText];
}

关于objective-c - 如何使用 NSTextview 实现撤销,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25590912/

相关文章:

swift - XCTestCase - 如何断言包含字符串的 NSTextView?

ios - 无法阻止搜索栏显示取消按钮

macos - Mac : There was an error while executing `VBoxManage` , Vagrant 使用的 CLI

macos - 如何在 NSTextView 中嵌入 subview ?

c++ - 在/usr/bin 中删除并复制回来后出现 Clang 错误

ios - 原始字符串的特殊字符 - Objective C

objective-c - 调整窗口大小时保持缩放后的 NSScrollView 的内容居中且可见

ios - 是否有获得延迟焦点状态的 api 语音?

ios - CGImageGetWidth(workingImage.CGImage) 和 workingImage.size.width 有区别吗?

objective-c - Objective C、UIGestureRecognizer的分配与释放