2016-11-15 16 views
1

我有一個基於NSDocument的應用程序工作正常 - 但現在我想給它一個客戶NSWindowController,以便我可以實現對它的NSTouchbar支持。如何爲NSDocument實現一個自定義的NSWindowController

到目前爲止,我剛剛使用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中創建一個新對象,並將窗口連接到它 - 但這不起作用。我的DocumentWindowController方法都不起作用。我很茫然!

幫助我堆棧溢出,你是我唯一的希望!

回答

1

How to Subclass NSWindowController

如何繼承NSWindowController

一旦你決定要繼承NSWindowController,您需要更改基於文檔的默認應用程序設置。首先,將您的文檔用戶界面的Interface Builder出口和動作添加到NSWindowController子類,而不是添加到NSDocument子類。 NSWindowController子類實例應該是nib文件的文件所有者,因爲這會在視圖相關邏輯和模型相關邏輯之間創建更好的分隔。一些菜單操作仍然可以在NSDocument子類中實現。例如,保存和恢復文檔由NSDocument實現,您可以添加自己的其他菜單操作,例如在文檔上創建新視圖的操作。

其次,不是在NSDocument子類中重寫windowNibName,而是覆蓋makeWindowControllers。在makeWindowControllers中,創建至少一個自定義NSWindowController子類的實例,並使用addWindowController:將其添加到文檔中。如果您的文檔始終需要多個控制器,請在此處創建它們。如果文檔可以支持多個視圖,但默認情況下有一個視圖,則可以在此處爲默認視圖創建控制器,並提供用於創建其他視圖的用戶操作。

您不應該強制窗口在makeWindowControllers中可見。如果合適的話,NSDocument會爲你做這件事。

+0

但如果我設置文件的所有者是我的窗控制器子類,會發生什麼情況的所有文件的所有者方法它們是文件,而不是特定的窗口?我是否爲文檔創建一個對象並在那裏連接那些方法? – headbanger

+0

連接到第一響應者或連接到窗口控制器的方法,並讓窗口控制器調用文檔的方法。 – Willeke

+0

謝謝你的建議。唉,它不起作用(我自己無能爲力,我敢肯定)。我在這裏放了一個測試版本https://github.com/HeadBanging/TouchTest - 你能提出我可能搞砸了嗎? – headbanger