子类化 NSTextView 使得在 Cocoa 中无法撤消

Subclassing NSTextView makes undo impossible in Cocoa

我有一个非常简单的 Cocoa 程序。一个 window,里面有一个 NSTextView。在此配置中,NSTextView 的运行完全符合您的预期。我可以键入、撤消、重做,一切。

但后来我子class NSTextView,我们就叫它TextView吧。这个新的 class 没有覆盖任何方法,它基本上是一个空白的 subclass。我用它的新 subclass 替换了 NSTextView。我可以在 TextView 中键入文本,但撤消不起作用。它只是对我发出哔哔声。撤消菜单项显示为灰色。我不希望发生这种情况,因为 TextView 不会向对象继承结构添加任何新代码。

我必须对我的 TextView 做什么才能重新启用撤消?

GitHub project

XIB object hierarchy, "Text View" is my "TextView" class

编辑:经过进一步观察,我的子class中确实有一个编辑导致了这个问题,正如 Mohamad Farhand 所认为的那样。

您可能需要启用 allowsUndo 属性 子classed TextView class。

@implementation TextView

- (nullable instancetype)initWithCoder:(nonnull NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        self.allowsUndo = YES;
    }
    return self;
}

@end

覆盖方法:shouldChangeTextInRange导致此问题

我建议您检查一下 link: Cocoa: looking for a general strategy for programmatic manipulation of NSTextView storage without messing up undo