在没有类的情况下,如何在Swift 2.2中为第一个响应者使用#selector? [英] How to use #selector in Swift 2.2 for the first responder, without a class?

查看:47
本文介绍了在没有类的情况下,如何在Swift 2.2中为第一个响应者使用#selector?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将doSomething发送到firstResponder,它可以是多个对象中的任何一个.

I want to send doSomething to the firstResponder, which could be any of several objects.

menuItem = NSMenuItem(title: "Do Something!",
                      action: Selector("doSomething"),
                      keyEquivalent: "")

我在Swift 2.2之前使用Selector("doSomething").我现在该怎么办?

I was using Selector("doSomething") prior to Swift 2.2. How do I do it now?

推荐答案

使用选择器doSomething创建一个协议,并使所有可以作为第一响应者的对象都遵循该协议.然后为您的课程实施选择器.

Create a protocol with the Selector doSomething and have all of your objects that can be first responders conform to it. Then implement the selector for your classes.

@objc protocol MyProtocol {
    func myCoolFuncThatManyObjectsRespondTo()
}

extension NSObject: MyProtocol {
    func myCoolFuncThatManyObjectsRespondTo() {
        print("Sup?")
    }
}

let menuItem = NSMenuItem(title: "Do Something!", action: #selector(MyProtocol.myCoolFuncThatManyObjectsRespondTo), keyEquivalent: "")

这篇关于在没有类的情况下,如何在Swift 2.2中为第一个响应者使用#selector?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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