我制作了一个带有按钮的应用程序,当您按下它时,它会被禁用,并且撤消操作应该将其返回到之前的状态(启用它)。我使用 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
我做错了什么?
最佳答案
我已经编辑了您的代码,希望我的示例对您有所帮助。
如果您仍有问题,请通知我 =)
#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
关于objective-c - NSUndoManager 基础知识,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25103881/