我试图在Swift中创建一个NSTimer,但我遇到了一些麻烦。

NSTimer(timeInterval: 1, target: self, selector: test(), userInfo: nil, repeats: true)

Test()是同一个类中的一个函数。


我在编辑器中得到一个错误:

无法找到一个超载的'init'接受提供的 参数

当我把selector: test()改为selector: nil时,错误就消失了。

我试过了:

选择器:测试() 选择器:测试 选择器:选择器(测试())

但是什么都没用,我在参考文献中找不到解决方案。


当前回答

自从Swift 3.0发布以来,它甚至更微妙地声明了一个targetAction合适

class MyCustomView : UIView {

    func addTapGestureRecognizer() {

        // the "_" is important
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(MyCustomView.handleTapGesture(_:)))
        tapGestureRecognizer.numberOfTapsRequired = 1
        addGestureRecognizer(tapGestureRecognizer)
    }

    // since Swift 3.0 this "_" in the method implementation is very important to 
    // let the selector understand the targetAction
    func handleTapGesture(_ tapGesture : UITapGestureRecognizer) {

        if tapGesture.state == .ended {
            print("TapGesture detected")
        }
    }
}

其他回答

对于未来的读者,我发现我遇到了一个问题,并得到了一个无法识别的选择器发送到实例错误,这是由标记目标func为私有引起的。

func必须是公开可见的,可以由引用选择器的对象调用。

Swift 2.2+和Swift 3更新

使用新的#selector表达式,它消除了使用字符串文字的需要,使使用更不容易出错。供参考:

Selector("keyboardDidHide:")

就变成了

#selector(keyboardDidHide(_:))

参见:快速进化提案

注意(Swift 4.0):

如果使用# selector,你需要将函数标记为@objc

例子:

@objc func something(_ sender: UIButton)

只是为了以防别人有同样的问题,我与NSTimer没有其他答案固定的问题,是真正重要的提到,如果你正在使用一个类,不继承从NSObject直接或深层的层次结构(例如。手动创建的swift文件),其他答案都不会工作,即使指定如下:

let timer = NSTimer(timeInterval: 1, target: self, selector: "test", 
                    userInfo: nil, repeats: false)
func test () {}

除了从NSObject继承类之外,没有改变任何其他东西,我停止了“Unrecognized selector”错误,并让我的逻辑按预期工作。

下面是一个关于如何在Swift上使用Selector类的快速示例:

override func viewDidLoad() {
    super.viewDidLoad()

    var rightButton = UIBarButtonItem(title: "Title", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("method"))
    self.navigationItem.rightBarButtonItem = rightButton
}

func method() {
    // Something cool here   
}

请注意,如果作为字符串传递的方法不起作用,它将在运行时失败,而不是在编译时失败,并使应用程序崩溃

斯威夫特4.1 与样本的轻拍手势

let gestureRecognizer = UITapGestureRecognizer()
self.view.addGestureRecognizer(gestureRecognizer)
gestureRecognizer.addTarget(self, action: #selector(self.dismiss(completion:)))

// Use destination 'Class Name' directly, if you selector (function) is not in same class.
//gestureRecognizer.addTarget(self, action: #selector(DestinationClass.dismiss(completion:)))


@objc func dismiss(completion: (() -> Void)?) {
      self.dismiss(animated: true, completion: completion)
}

有关选择器表达式的更多细节,请参阅Apple的文档