@selector() in Swift?

后端 未结 23 2540
清酒与你
清酒与你 2020-11-21 15:24

I\'m trying to create an NSTimer in Swift but I\'m having some trouble.

NSTimer(timeInterval: 1, target: self, selector: test(), us         


        
23条回答
  •  迷失自我
    2020-11-21 16:15

    you create the Selector like below.
    1.

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

    2.

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

    Take note that the @selector syntax is gone and replaced with a simple String naming the method to call. There’s one area where we can all agree the verbosity got in the way. Of course, if we declared that there is a target method called flatButtonPressed: we better write one:

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

    set the timer:

        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
    

    In order to be complete, here’s the flatButtonPressed

    func flatButtonPressed(timer: NSTimer) {
    }
    

提交回复
热议问题