如何为NSDocument实现自定义NSWindowController

时间:2016-11-15 15:47:24

标签: objective-c cocoa nswindowcontroller

我有一个基于NSDocument的应用程序工作正常 - 但现在我想给它一个客户NSWindowController,以便我可以实现它的NSTouchbar支持。

到目前为止,我刚刚使用了NSDocument提供的标准NSWindowController - 所以这不是我有任何经验的。我已经实现了NSWindowController的存根,我认为这应该足够了:

(document.h)

#import <Cocoa/Cocoa.h>

@interface DocumentWindowController : NSWindowController

@end

@interface Document : NSDocument
.
.
.

(document.m)

static NSTouchBarItemIdentifier WindowControllerLabelIdentifier = @"com.windowController.label";

@interface DocumentWindowController () <NSTouchBarDelegate>

@end

@implementation DocumentWindowController

- (void)windowDidLoad
{
    [super windowDidLoad];
}

- (NSTouchBar *)makeTouchBar
{
    NSTouchBar *bar = [[NSTouchBar alloc] init];
    bar.delegate = self;

    // Set the default ordering of items.
    bar.defaultItemIdentifiers = @[WindowControllerLabelIdentifier, NSTouchBarItemIdentifierOtherItemsProxy];

    return bar;
}

- (nullable NSTouchBarItem *)touchBar:(NSTouchBar *)touchBar makeItemForIdentifier:(NSTouchBarItemIdentifier)identifier
{
    if ([identifier isEqualToString:WindowControllerLabelIdentifier])
    {
        NSTextField *theLabel = [NSTextField labelWithString:@"Test Document"];

        NSCustomTouchBarItem *customItemForLabel =
        [[NSCustomTouchBarItem alloc] initWithIdentifier:WindowControllerLabelIdentifier];
        customItemForLabel.view = theLabel;

        // We want this label to always be visible no matter how many items are in the NSTouchBar instance.
        customItemForLabel.visibilityPriority = NSTouchBarItemPriorityHigh;

        return customItemForLabel;
    }

    return nil;
}

@end

@implementation Document
.
.
.

但现在我不知道如何连接它以便我的NSWindowController(DocumentWindowController)被NSDocument使用。我已经尝试在xib中创建一个新对象并将Window连接到它 - 但这不起作用。我的DocumentWindowController方法都不起作用。我不知所措!

帮我Stack Overflow,你是我唯一的希望!

1 个答案:

答案 0 :(得分:1)

来自How to Subclass NSWindowController

  

如何对NSWindowController进行子类化

     

一旦您决定继承NSWindowController,您需要更改默认的基于文档的应用程序设置。首先,将文档用户界面的任何Interface Builder出口和操作添加到NSWindowController子类而不是NSDocument子类。 NSWindowController子类实例应该是nib文件的文件所有者,因为这样可以在视图相关逻辑和模型相关逻辑之间创建更好的分离。某些菜单操作仍可在NSDocument子类中实现。例如,“保存”和“还原文档”由NSDocument实现,您可以添加自己的其他菜单操作,例如用于在文档上创建新视图的操作。

     

其次,不要覆盖NSDocument子类中的windowNibName,而是覆盖makeWindowControllers。在makeWindowControllers中,创建自定义NSWindowController子类的至少一个实例,并使用addWindowController:将其添加到文档中。如果您的文档始终需要多个控制器,请在此处创建它们。如果文档可以支持多个视图但默认情况下有一个,则在此处为默认视图创建控制器,并为创建其他视图提供用户操作。

     

您不应强制窗口在makeWindowControllers中可见。如果合适,NSDocument会为您做到这一点。