NSWindowController не скрывает свое окно при инициализации? - PullRequest
1 голос
/ 20 мая 2011

У меня есть подкласс NSDocument с двумя NSWindowController, соответствующими 2 различным xib.

Следуя Руководству по применению на основе документов, я добавил следующее в мою реализацию document.m

- (void)makeWindowControllers 
{
    NSLog(@"in MakeWindowControllers");

    MainWindowController *mainWindowController = [[MainWindowController alloc] init];
    [mainWindowController autorelease];
    [self addWindowController:mainWindowController];

    csvWindowController = [[CSVWindowController alloc] init];
    [csvWindowController autorelease];
    [self addWindowController:csvWindowController];        
}

Проблема в том, что я хочу, чтобы второй оконный контроллер csvWindowController изначально скрывал свое окно, позже я покажу тот же экземпляр окна.Для этого я написал:

@implementation CSVWindowController


- (id) init {

    if ( ! (self = [super initWithWindowNibName:@"CSVWindow"]) ) {

        NSLog(@"CSVWindowController init failed");
        return nil;
    }

    window = [self window];
    NSLog(@"CSVWindowController init");

    [window orderOut:nil]; // to hide it
    NSLog(@"CSVWindowController hiding the window");

    return self;
}

Но окно там, показывает вверх.

Пожалуйста, не отмечайте, что VisibleAtLaunch не помечен, что консоль показывает мои сообщения правильно, и чтодаже если я изменю:

        [window orderOut:nil]; // to hide it
to 
        [window orderOut:self]; // to hide it

Результат тот же, окно отображается.

Любая помощь приветствуется, спасибо:)

1 Ответ

1 голос
/ 22 мая 2011

Хорошо, я снова отвечаю на свой вопрос, но на этот раз с положительным замечанием.Я думаю, что то, что я делал неправильно, было связано со скрытыми для меня последствиями основанной на документе архитектуры стандартного шаблона приложения для документов.

Я пробовал с другим подходом, создавая приложение изСкретч НЕ помечает «Приложение на основе документа» и предоставляет ему:

  • 1 Подкласс NSDocument
  • 2 Подклассы NSWindowControllers
  • 1 MainMenu.xib
  • 2 window.xib

и я принудительно создал экземпляры подклассов NSWindowController в коде MyDocument.

Я также поместил IBActions для MenuItems в MyDocument, и я привязалобъект MyDocument для MenuItems в MainMenu.xib.

На этот раз я смог сделать что угодно, скрыть / показать окна, начиная с одного скрытого, а не включать элементы меню автоматически по желанию.

Ниже приведен код для любого новичка, как я, которому, возможно, придется бороться с этим в будущем.,

//  MyDocument.h
#import <Cocoa/Cocoa.h>
#import "testWindowController.h"
#import "test2WindowController.h"

@interface MyDocument : NSDocument {
    testWindowController *test;
    test2WindowController *test2;

}

- (IBAction)showWindow1:(id)pId;
- (IBAction)showWindow2:(id)pId;
- (IBAction)hideWindow1:(id)pId;
- (IBAction)hideWindow2:(id)pId;

@end


//  MyDocument.m
#import "MyDocument.h"
#import "testWindowController.h"
#import "test2WindowController.h"

@implementation MyDocument

- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
        NSLog(@"MyDocument init...");
        [self makeWindowControllers];
    }

    return self;
}

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

- (void)makeWindowControllers 
{

    test = [[testWindowController alloc] init];
    test2 = [[test2WindowController alloc] init];  

    [self addWindowController:test];
    [self addWindowController:test2];

    // start hiding the first window
    [[test window] orderOut:self];
}

- (IBAction)hideWindow1:(id)pId
{
    NSLog(@"hideWindow1");
    [[test window] orderOut:self];
}

- (IBAction)showWindow1:(id)pId
{
    NSLog(@"showWindow1");
    [test showWindow:self];
    [[test window] makeKeyAndOrderFront:nil]; // to show it
}

- (IBAction)hideWindow2:(id)pId
{
    NSLog(@"hideWindow2");
    [[test2 window] orderOut:self];
}

- (IBAction)showWindow2:(id)pId
{
    NSLog(@"showWindow2");
    [test2 showWindow:self];
    [[test2 window] makeKeyAndOrderFront:nil]; // to show it
}


 -(BOOL)validateMenuItem:(NSMenuItem *)menuItem {

     NSLog(@"in validateMenuItem for item: %@", [menuItem title]);

     if ([[menuItem title] isEqualToString:@"Show Window"] 
         && [[test window] isVisible]){
         return NO;
     }

     if ([[menuItem title] isEqualToString:@"Hide Window"] 
         && ![[test window] isVisible]){
         return NO;
     }

     if ([[menuItem title] isEqualToString:@"Show Window2"] 
         && [[test2 window] isVisible]){
         return NO;
     }

     if ([[menuItem title] isEqualToString:@"Hide Window2"] 
         && ![[test2 window] isVisible]){
         return NO;
     }
     return [super validateMenuItem:menuItem];
 }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...