【问题标题】:Stopping modal when window is closed (Cocoa)窗口关闭时停止模式(可可)
【发布时间】:2010-01-05 23:15:41
【问题描述】:

我目前正在使用此代码显示模式窗口:

[[NSApplication sharedApplication] runModalForWindow:mainWindow];

但是,当我关闭此窗口时,其他窗口仍处于非活动状态。使用“red x”关闭窗口时如何运行stopModal方法?

谢谢,

迈克尔

【问题讨论】:

    标签: cocoa modal-dialog nswindow


    【解决方案1】:

    您可以为窗口创建一个委托并让它响应
    -(void)windowWillClose:(NSNotification *)notification 或
    - (void )windowShouldClose:(NSNotification *)notification 方法如下:

    - (void)windowWillClose:(NSNotification *)notification {
       [[NSApplication sharedApplication] stopModal];
    }
    

    见Mac Dev Center: NSWindowDelegate Protocol Reference

    【讨论】:

      【解决方案2】:

      如果您有一个应用于特定窗口的对话框,那么您可能不应该使用模态对话框,而是使用工作表。如果可能,应避免使用模态对话框。如果您使用工作表,那么您遇到的问题将不再是问题。

      - (void)showSheet:(id)sender
      {
          [NSApp beginSheet:yourModalWindow 
              modalForWindow:windowThatSheetIsAttachedTo
              modalDelegate:self
              didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:) 
                 contextInfo:nil];
      }
      
      - (void)sheetDidEnd:(NSWindow *)sheet returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo
      {
          [sheet orderOut:self];
          [NSApp endSheet:sheet];
      }
      

      【讨论】:

        【解决方案3】:

        除了 Randall 的回答,您还可以将控制器类链接为 .xib 文件中定义的窗口的委托。

        你可以处理

        [[NSApplication sharedApplication] stopModal];
        

        在任一

        • -(void)performClose:(id)sender

        • -(void)windowWillClose:(NSNotification *)notification

        方法。

        【讨论】:

          【解决方案4】:

          Swift 4(注意之前的方法已弃用):

          window.beginSheet(self.uiSettingsPanel, completionHandler: {response in
                  NSLog("Finished sheet, response: \(response)")
          })
          

          其中 self.uiSettingsPanel 是 NSPanel 子类的实例。然后,在工作表的 NSPanel 子类中,用类似的东西关闭它

          @IBAction func buttonOK(_ sender: NSButton) {
              self.sheetParent!.endSheet(self, returnCode: .OK)
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-11-29
            • 1970-01-01
            • 2012-04-11
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多