具有多个字段的撤消管理器

问题描述 投票:0回答:1

您好,我有一个应用程序,它非常基本,但有一些地址字段,例如城市、邮政编码、州等...

我希望用户可以跨多个字段撤消内容,目前默认撤消仅适用于您正在使用的字段。我在我的字段中使用 NSTextFields。

我假设我需要使用 UndoManager 但我不确定如何在我的字段上实现它,我的字段有 ID。是否有任何关于如何执行此操作的文档,所有字段都没有任何功能 - 我只是从按钮事件之一的所有字段中获取数据。

我不知道 swift,所以请用 Obj-c 回复,以便我可以理解需要做什么。

objective-c nstextfield nsundomanager
1个回答
0
投票

这里有一个小例子可以帮助您入门。

  1. 从 Xcode macOS 应用程序模板开始。
  2. 将以下代码添加到AppDelegate.m。
  3. 向窗口添加一些控件(
    NSTextField
    NSControl
    的另一个子类)。
  4. 将控件的操作连接到
    controlAction:
@interface AppDelegate ()

@property (strong) IBOutlet NSWindow *window;

// values before editing, the key is the identifier of the control
@property (strong) NSMutableDictionary *data;

@end


@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    self.data = [[NSMutableDictionary alloc] init];
}

- (void)undoControl:(NSControl *)control oldValue:(id)oldValue newValue:(id)newValue {
    // undo
    NSString *controlID = control.identifier;
    [control setObjectValue:oldValue];
    self.data[controlID] = oldValue;
    if (control.acceptsFirstResponder)
        [self.window makeFirstResponder: control];
    // register redo
    NSLog(@"register redo %@ old:'%@' new:'%@'", controlID, oldValue, newValue);
    [[self.window.undoManager prepareWithInvocationTarget:self] undoControl:control
        oldValue:newValue newValue:oldValue];
}

- (IBAction)controlAction:(NSControl *)control {
    NSString *controlID = control.identifier;
    id oldValue = self.data[controlID];
    id newValue = control.objectValue;
    if (oldValue != newValue && ![oldValue isEqual:newValue]) {
        // register undo
        NSLog(@"register undo %@ old:'%@' new:'%@'", controlID, oldValue, newValue);
        [[self.window.undoManager prepareWithInvocationTarget:self] undoControl:control
            oldValue:oldValue newValue:newValue];
        self.data[controlID] = newValue;
    }
}

@end
© www.soinside.com 2019 - 2024. All rights reserved.