Swift NSWindow shows up and disappears immediately

家住魔仙堡 提交于 2021-02-08 04:57:17

问题


I'm a complete beginner to Swift, so this may be a silly question, but I can't figure out how this works...

I have a view with a button inside which calls the following code:

let window = NSWindow()
window.center()
window.title = "test"
window.makeKeyAndOrderFront(self)

When I click the button the window opens just for a moment and disappears a few milliseconds later.

Can anyone help me with that? It seems I have a quite serious misunderstanding about views in Cocoa ;-)

Thanks Tom


回答1:


The problem is that you are creating and 'storing' the NSWindow in your button action function. That means that as soon as that button action is done, the NSWindow will go out of context, and be released and thus disappear.

This is how the memory management in Swift works: as soon as nobody owns an object anymore, it will be released.

What you should do is put your window in an instance variable. Like for example:

class YourViewController: NSViewController {
    private var window: NSWindow!

    @IBAction func buttonAction(sender: UIButton) {
        window = NSWindow()
        window.center()
        window.title = "test"
        window.makeKeyAndOrderFront(self)    
    }
}

The hint about makeKeyAndOrderFront(nil) makes no difference. Passing either nil or self is fine. But latter, how you did it originaly, makes more sense.



来源:https://stackoverflow.com/questions/29399693/swift-nswindow-shows-up-and-disappears-immediately

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!