Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 倒计时计时器将不工作,因为它不接受本地功能_Swift_Xcode_Countdown - Fatal编程技术网

Swift 倒计时计时器将不工作,因为它不接受本地功能

Swift 倒计时计时器将不工作,因为它不接受本地功能,swift,xcode,countdown,Swift,Xcode,Countdown,每次我尝试在使用Timer.Scheduledtimer和选择器时定义函数时。它显示以下错误。我不知道该怎么过去。另外,我想知道我是否可以将标签连接到倒计时,即屏幕上的0:59、0:58等 谢谢 我已经尝试了不同网站的各种功能,同样的问题总是会再次出现 var seconds = 0 var timer: Timer? let countdownLabel: SKLabelNode! = { let label = SKLabelNode(fontNamed: "BubbleGum")

每次我尝试在使用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注释
计数器
函数,要么使用闭包

@objc func counter () {
   ...
}
使用闭包:

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

我也试过了,但出现了另一个错误:@objc只能用于类的成员、objc协议和类的具体扩展。这是否意味着我必须使用特定的objective c类?我希望您已经在class@Drobotjosh你能给我看更多的这个类,包括viewdidload和imports吗?这不是必需的,因为它现在正在工作。但是如果你想知道的话。我已经进口了SpriteKit和GamePlayKit