Swift中的NSApplication子类 [英] Subclass NSApplication in Swift

查看:173
本文介绍了Swift中的NSApplication子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了NSApplication子类:

I created NSApplication subclass:

class MyApplication: NSApplication {
    override func sendEvent(theEvent: NSEvent) {
        if theEvent.type == NSEventType.KeyUp && (theEvent.modifierFlags & .CommandKeyMask).rawValue != 0 {
            self.keyWindow?.sendEvent(theEvent)
        } else {
            super.sendEvent(theEvent)
        }
    }
}

此后,我将Info.plist中的"Principal class"更改为MyApplication,最后在Main.storyboard的Application Scene中,我也将Application更改为MyApplication.

After that, I changed "Principal class" in Info.plist to MyApplication and at the end in the Application Scene in Main.storyboard, I changed Application to MyApplication, too.

运行应用程序时,我收到以下消息:

When I run application I get following message:

找不到类:MyApplication,正在退出

Unable to find class: MyApplication, exiting

有人可以帮我吗?

推荐答案

尝试:

@objc(MyApplication)
class MyApplication: NSApplication {

或者,您必须像这样设置Info.plist.

OR, you have to set Info.plist like this.

<key>NSPrincipalClass</key>
<string>YourAppName.MyApplication</string>
        ^^^^^^^^^^^^

目前没有确切的文档,但是

There is no exact document about this, but this description is corresponding:

为了在Objective-C代码中使用Swift类时保留命名空间,Swift类以其完全限定的名称公开给Objective-C运行时.因此,当您使用对Swift类的字符串表示形式进行操作的API时,必须包括该类的完全限定名称.例如,当您创建基于文档的Mac应用程序时,可以在应用程序的 Info.plist 文件中提供NSDocument子类的名称.在Swift中,您必须使用文档子类的全名,包括从应用程序或框架的名称派生的模块名称.

In order to preserve namespacing when a Swift class is used in Objective-C code, Swift classes are exposed to the Objective-C runtime with their fully qualified names. Therefore, when you work with APIs that operate on the string representation of a Swift class, you must include the fully qualified name of the class. For example, when you create a document–based Mac app, you provide the name of your NSDocument subclass in your app’s Info.plist file. In Swift, you must use the full name of your document subclass, including the module name derived from the name of your app or framework.

在Swift类上使用@objc(<#name#>)属性时,该类可在Objective-C中使用,而无需任何命名空间.

When you use the @objc(<#name#>) attribute on a Swift class, the class is made available in Objective-C without any namespacing.

这篇关于Swift中的NSApplication子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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