倒数计时器将无法使用,因为它不接受本地功能

时间:2019-06-10 08:14:40

标签: swift xcode countdown

每当我使用带有选择器的Timer.Scheduledtimer时,我都会尝试定义一个函数。它显示以下错误。我不确定该如何解决。我也想知道是否我可以将标签连接到倒计时,即在屏幕0:59、0:58等上

谢谢。

我已经尝试过来自不同网站的各种功能,并且始终会出现相同的问题

var seconds = 0

var timer: Timer?

let countdownLabel: SKLabelNode! = {   
let label = SKLabelNode(fontNamed: "BubbleGum")
   label.zPosition = 2
   label.color = SKColor.white
   label.position = CGPoint(x: 0 - 130, y:self.frame.size.height/15 
+ 390)
   return label
    }()
    countdownLabel.text = String(seconds)

    func counter (){
        seconds -= 1
        countdownLabel.text = String(seconds)
        if (seconds == 0)
        {
            timer!.invalidate()
        }

    }


    timer = Timer.scheduledTimer(timeInterval: 1, target: self, 
  selector: #selector(counter), userInfo: nil, repeats: true)



    self.addChild(countdownLabel)



}

这是出现的错误消息:     “ #selector”的参数不能引用本地函数“ counter()”

2 个答案:

答案 0 :(得分:1)

要么用@objc注释counter函数,要么使用闭包

@objc func counter () {
   ...
}

使用闭包:

timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) { timer in
    seconds -= 1
    countdownLabel.text = String(seconds)
    if (seconds == 0)
    {
        timer!.invalidate()
    }
}

答案 1 :(得分:0)

您必须在函数前面添加@objc。如果要在选择器中调用函数,请务必记住在函数中添加@objc

class ViewControlller: UIViewController {

        override func viewDidLoad() {
            super.viewDidLoad()
            //call it like this in viewdidload/viewdidappear
            timer = Timer.scheduledTimer(timeInterval: 1, target: self, 
      selector: #selector(counter), userInfo: nil, repeats: true)
        }


      //Declare this function outside any other func like viewdidload/viewdidappear
      @objc func counter(){
            seconds -= 1
            countdownLabel.text = String(seconds)
            if (seconds == 0)
            {
                timer!.invalidate()
            }

        }

}