Objective-C首选项窗口makeKeyAndOrderFront或showWindow?

ahm*_*106 3 macos cocoa objective-c

我正在开发一个新的Mac应用程序,想打开我的首选项窗口,我有2个Nib(xib)文件,一个用于主窗口,一个用于首选项窗口,然后我有一个openPreferences Action,它显示了首选项窗口,某事.像这样:

- (IBAction)openPreferences:(id)sender
{
    PrefCont *cont = [[PrefCont alloc] init];
    [cont showWindow:self];
}
Run Code Online (Sandbox Code Playgroud)

此代码有效,但是当我在打开的"首选项菜单项"上单击多次,然后"首选项"窗口打开两次或更多次,然后两次.

有没有可能做到这一点.像makeKeyAndOrderFront但它必须由PrefController调用?

或者我可以问Mac窗口是否打开?如果没有,那么显示它或者...... 链接这个.

感谢大家,这将非常有用!

Dav*_*ong 6

如果你想避免双窗口症状,你应该制作PrefCont * cont这个类的ivar,然后执行:

- (IBAction) openPreferences:(id)sender {
  if (cont == nil) {
    cont = [[PrefCont alloc] init];
  }
  [cont showWindow:sender];
}
Run Code Online (Sandbox Code Playgroud)

这样你只会创建一个首选项控制器,并告诉它一个显示它的窗口.

不要忘记[cont release];你什么时候完成......


Ken*_*agh 5

更好的方法是让PrefCont类具有单例例程,如:

+(PrefCont*)prefs
{
  static PrefCont* prefs = nil;
  if (!prefs)
     prefs = [[PrefCont alloc] init];

  return prefs;
}
Run Code Online (Sandbox Code Playgroud)

然后每当你想显示偏好时,只需打电话

  [[PrefCont prefs] showWindow:sender];
Run Code Online (Sandbox Code Playgroud)