小编use*_*667的帖子

如何通过编程NSTextView的textValue来实现undo/redo?

我用NSTextView和一个按钮创建了一个简单的演示应用程序,为textView提供了一个NSTextViewDelegate并添加了一个动作:

- (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];
}
Run Code Online (Sandbox Code Playgroud)

如果我手动更改文本,撤消/重做没有问题.但是,如果我使用action方法更改文本,则undo会按预期工作,但redo不再起作用(没有任何反应),并且撤消管理器似乎被加扰...

好的 - 为了避免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"]; …
Run Code Online (Sandbox Code Playgroud)

cocoa undo-redo nstextview

10
推荐指数
2
解决办法
3678
查看次数

标签 统计

cocoa ×1

nstextview ×1

undo-redo ×1