我创建了一个简单的演示应用程序,其中包括一个NSTextView和一个按钮,提供了一个NSTextViewDelegate给textView,并添加了一个操作:
- (IBAction)actionButtonClicked:(id)sender {
NSString *oldText = [[[self.textView textStorage] string] copy];
NSString *newText = @"And... ACTION!";
[[self.textView undoManager] registerUndoWithTarget:self.textView
selector:@selector(setString:)
object:oldText];
[[self.textView undoManager] setActionName:@"ACTION"];
[self.textView setString:newText];
}
如果我通过手动更改文本,撤销/重做功能可以正常工作。但是如果我使用操作方法来更改文本,则撤销功能按预期工作,但重做功能不再起作用(没有任何反应),撤销管理器似乎被破坏了......
为了避免与NSTextView的问题,我创建了一个模型类,将NSTextView绑定到它上面,并将撤销/重做移动到了模型中,但是这显示出了与之前相同的行为 - 我做错了什么 - 这应该很容易解决,不是吗?
#import "GFTextStore.h"
@implementation GFTextStore
@synthesize textVal = textVal_;
-(void)changeText{
if (!undoMan_) {
undoMan_ = [[[NSApplication sharedApplication] mainWindow] undoManager];
}
NSAttributedString *oldText = [self.textVal copy];
NSString *tempStr = [[oldText string] stringByAppendingFormat:@"\n%@",[[NSCalendarDate date]description]];
NSAttributedString *newText = [[NSAttributedString alloc] initWithString:tempStr];
[self setTextVal:newText];
[undoMan_ registerUndoWithTarget:self
selector:@selector(setTextVal:)
object:oldText];
[undoMan_ setActionName:@"ACTION"];
}
@end