【问题标题】:NSUndoManager basicsNSUndoManager 基础知识
【发布时间】:2014-08-03 10:41:45
【问题描述】:

我制作了一个带有按钮的应用程序,当您按下它时,它会被禁用,撤消操作应将其返回到以前的状态(启用它)。我使用 NSUndoManager 使这成为可能,但它不起作用。我的应用中似乎缺少一些重要的东西,但我找不到确切的东西。

AppDelegate.h:

#import <Cocoa/Cocoa.h>

@interface AppDelegate : NSObject <NSApplicationDelegate>
{
    NSUndoManager* undoManager;
}

@property (assign) IBOutlet NSWindow *window;
@property (weak) IBOutlet NSButton *button;
- (IBAction)Disable:(id)sender;

@end

AppDelegate.m:

#import "AppDelegate.h"

@implementation AppDelegate

@synthesize window = _window;

- (NSUndoManager*)windowWillReturnUndoManager:(NSWindow*)window
{
    return undoManager;
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{

}

- (id) init
{
    if(self = [super init])
        undoManager = [[NSUndoManager alloc]init];
    return self;
}


- (IBAction)Disable:(id)sender
{
    [[undoManager prepareWithInvocationTarget:self]Enable];
    [_button setEnabled:NO];
    if (![undoManager isUndoing])
        [undoManager setActionName:@"Disable"];
}

-(void)Enable
{
    [[undoManager prepareWithInvocationTarget:self]Disable:self];
    [_button setEnabled:YES];
    if (![undoManager isUndoing])
        [undoManager setActionName:@"Enable"];
}
@end

我做错了什么?

【问题讨论】:

    标签: objective-c xcode undo nsundomanager


    【解决方案1】:

    我已经编辑了您的代码,希望我的示例对您有所帮助。

    如果您仍然有问题,请通知我 =)

    #import "AppDelegate.h"
    
    @interface AppDelegate ()
    {
        NSUndoManager* undoManager;
    }
    @property (weak) IBOutlet NSWindow *window;
    @property (weak) IBOutlet NSButton *button;
    @property (weak) IBOutlet NSButton *undoButton;
    
    @end
    
    @implementation AppDelegate
    
    - (NSUndoManager*)windowWillReturnUndoManager:(NSWindow*)window
    {
        return undoManager;
    }
    
    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
    {
        undoManager = [[NSUndoManager alloc]init];
        [self update];
    }
    
    - (IBAction)Disable:(id)sender
    {
        [[undoManager prepareWithInvocationTarget:self]Enable];
        [_button setEnabled:NO];
        if (![undoManager isUndoing])
            [undoManager setActionName:@"Disable"];
        [self update];
    }
    
    - (IBAction)undo:(id)sender
    {
        [undoManager undo];
        [self update];
    }
    
    -(void)Enable
    {
        [[undoManager prepareWithInvocationTarget:self]Disable:self];
        [_button setEnabled:YES];
        if (![undoManager isUndoing])
            [undoManager setActionName:@"Enable"];
        [self update];
    }
    
    - (void)update
    {
        self.undoButton.title = [undoManager canUndo]?@"Undo":@"Can't undo";
    }
    
    @end
    

    【讨论】: