通过单击Swift中的按钮显示/隐藏窗口

时间:2015-08-31 08:53:01

标签: macos swift cocoa nswindowcontroller

我想通过单击主窗口中的按钮来快速显示/隐藏窗口。 Beginsheet显示窗口,但是endheet没有关闭窗口。我的appdelegate代码给出了:

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var window: NSWindow!


    func applicationDidFinishLaunching(aNotification: NSNotification) {
        // Insert code here to initialize your application
    }

    func applicationWillTerminate(aNotification: NSNotification) {
        // Insert code here to tear down your application
    }

    var settingsController: SettingsController?

    @IBAction func inSettings(sender: NSObject?)
    {
        settingsController = SettingsController(windowNibName: "SettingsController")
        window.beginSheet(settingsController!.window!, completionHandler: nil)
    }
    @IBAction func outSettings(sender: NSObject?)
    {
        window.endSheet(settingsController!.window!)
    }

}

SettingsController:

import Cocoa

class SettingsController: NSWindowController {

    override func windowDidLoad() {
        super.windowDidLoad()

        // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
    }
}

2 个答案:

答案 0 :(得分:2)

Swift 3解决方案:

让我们说你有WindowA和WindowB。您想要打开WindowB,但首先要隐藏WindowA。 用segue连接窗户。 (选择“显示”为segues“Kind”属性)并且您需要一个静态类来保持隐藏窗口。在WindowA中覆盖shouldPerformSegue并将WindowA保持为静态NSWindow对象。

 override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {

        YourStaticClass.WindowA = self.view.window
        self.view.window?.orderOut(self)

        return true
    }

orderOut(self)隐藏窗口。然后将打开WindowB。

在WindowB的视图控制器中,使用一个函数来关闭windowB并显示隐藏的WindowA:

 @IBAction func btnBack_Click(_ sender: NSButton) {  

    YourStaticClass.WindowA?.makeKeyAndOrderFront(YourStaticClass.WindowA)    
    self.view.window?.close()
}

答案 1 :(得分:0)

使用endSheet结束文档模式表会话。像这样:

@IBAction func outSettings(sender: NSObject?)
{
    settingsController!.window!.endSheet(settingsController!.window!)
}

编辑:您需要在调用orderOut的完成处理程序中关闭窗口,如下所示:

@IBAction func inSettings(sender: NSObject?)
{
    settingsController = SettingsController(windowNibName: "SettingsController")
    window.beginSheet(settingsController!.window!) {
        settingsController!.window!.orderOut(nil)
    }
}