倒数计时器将不起作用,因为它不接受本地功能

The countdown timer will not work because it will not accept local functions

每次当我使用带选择器的 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()'

您必须在您的函数前添加@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()
            }

        }

}

使用@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()
    }
}