Swift NSWindow出现并立即消失 [英] Swift NSWindow shows up and disappears immediately

查看:69
本文介绍了Swift NSWindow出现并立即消失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Swift的初学者,所以这可能是一个愚蠢的问题,但是我不知道这是如何工作的...

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 ;-)

谢谢汤姆

推荐答案

问题是您正在按钮操作函数中创建并存储" NSWindow .这意味着一旦完成该按钮操作, NSWindow 就会脱离上下文,并被释放并因此消失.

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.

这就是Swift中内存管理的工作方式:只要没有人再拥有一个对象,它就会被释放.

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)    
    }
}

关于 makeKeyAndOrderFront(nil)的提示没有区别.传递 nil 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.

这篇关于Swift NSWindow出现并立即消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆