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

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

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


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

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

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

我试过了:

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

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


当前回答

Swift 2.2+和Swift 3更新

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

Selector("keyboardDidHide:")

就变成了

#selector(keyboardDidHide(_:))

参见:快速进化提案

注意(Swift 4.0):

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

例子:

@objc func something(_ sender: UIButton)

其他回答

斯威夫特4.0

创建如下所示的选择器。

1.将事件添加到如下按钮:

button.addTarget(self, action: #selector(clickedButton(sender:)), for: UIControlEvents.touchUpInside)

函数如下所示:

@objc func clickedButton(sender: AnyObject) {

}

更改为调用选择器语法的方法中的简单字符串命名

var timer1 : NSTimer? = nil
timer1= NSTimer(timeInterval: 0.1, target: self, selector: Selector("test"), userInfo: nil, repeats: true)

之后,输入func test()。

斯威夫特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的文档

选择器在Swift 4:

button.addTarget(self, action: #selector(buttonTapped(sender:)), for: UIControlEvents.touchUpInside)

创建如下所示的选择器。 1.

UIBarButtonItem(
    title: "Some Title",
    style: UIBarButtonItemStyle.Done,
    target: self,
    action: "flatButtonPressed"
)

2.

flatButton.addTarget(self, action: "flatButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside)

注意,@selector语法消失了,取而代之的是一个简单的String来命名要调用的方法。有一个方面,我们都同意冗长是一个障碍。当然,如果我们声明有一个名为flatButtonPressed的目标方法:我们最好写一个:

func flatButtonPressed(sender: AnyObject) {
  NSLog("flatButtonPressed")
}

设置定时器:

    var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, 
                    target: self, 
                    selector: Selector("flatButtonPressed"), 
                    userInfo: userInfo, 
                    repeats: true)
    let mainLoop = NSRunLoop.mainRunLoop()  //1
    mainLoop.addTimer(timer, forMode: NSDefaultRunLoopMode) //2 this two line is optinal

为了完整,这里是flatButtonPressed

func flatButtonPressed(timer: NSTimer) {
}