2011-09-21 37 views
0

我的應用程序有「首選項」窗口。我打開使用此代碼它如何打開一個窗口「首選項」?

- (IBAction)openPreferences:(id)sender { 

    NSWindowController *windowController = [[NSWindowController alloc] initWithWindowNibName:@"Preferences"]; 
    [windowController window]; 
} 

如果按命令,一次,一次又一次新的Preferences窗口將被再次,一次又一次地打開......

如何打開只有一個窗口?謝謝!

回答

5

讓windowController AppDelegate中的實例變量和更改打開的喜好來

- (IBAction)openPreferences:(id)sender 
{ 
    if(windowController == nil) 
     windowController = [[NSWindowController alloc] initWithWindowNibName:@"Preferences"]; 
    [windowController showWindow:sender]; 
} 
+0

謝謝!你真的幫我! –

+0

我需要幫助!當我使用上面的評論代碼時,在我的應用程序中,我可能只打開一個「首選項」窗口。那就對了!!!但!當我關閉他時,再次按下「命令」,這不起作用。如何解決它? –

+0

在該窗口的界面生成器中,確保'關閉時釋放'未被選中,這樣當關閉時他的剛纔隱藏的首選項窗口就會被隱藏起來。 –

0

所以這是我如何解決它...... 我有一個類「MyPreferencesWindowController」其中有一個叫getInstance方法。這個方法就是你想要獲得偏好窗口時所調用的方法。該解決方案利用單件技術。

/** 
Method in my MyPreferencesWindowController.m file 
with a corresponding method in the .h file. 
*/ 
+(id) getInstance { 

    static PreferencesWindowController *instance = nil; 
    static dispatch_once_t onceToken; 

    dispatch_once(&onceToken, ^{ 
     instance = [[self alloc] init]; 
    }); 
    return instance; 
} 

現在在文檔類,如果你想顯示首選項窗口,請執行以下操作:

-(IBAction) showPreferences:(id)sender { 
    if (preferencesWc == nil) 
     preferencesWc = [MyPreferencesWindowController getInstance]; 

    [ preferencesWc showWindow:self ]; 
} 

這將確保只創建一次Preferences窗口。然後每次撥打getInstance將返回窗口的相同實例。

相關問題