如何在swift中每秒执行一次函数?

Rya*_*len 50 ios sprite-kit swift

我想在我正在制作的游戏中添加一个得分到我的场景顶部.分数将根据您的持续时间而定,并且每秒都会增加.我在这里先向您的帮助表示感谢!

import SpriteKit

class easyScene: SKScene {
let scrollBarEasyBottom = SKSpriteNode(imageNamed: "scrollBarEasyBottom")
let scrollBarEasyTop = SKSpriteNode(imageNamed: "scrollBarEasyTop")
let ball = SKSpriteNode(imageNamed: "ball")
var origSBEBpositionX = CGFloat(0)
var origSBETpositionX = CGFloat(0)
var maxSBEBX = CGFloat(0)
var SBEBSpeed = 5
var maxSBETX = CGFloat(0)
var SBETSpeed = 5
var score = 0
var timer: NSTimer?

var scoreText = SKLabelNode(fontNamed: "Kailasa")

 override func didMoveToView(view: SKView) {
    println("Easy Scene is the location")
    self.backgroundColor = UIColor.blackColor()
    self.scrollBarEasyBottom.position = CGPoint(x:0, y:270)
    self.addChild(self.scrollBarEasyBottom)
    self.scrollBarEasyBottom.yScale = 0.2
    self.origSBEBpositionX = self.scrollBarEasyBottom.position.x
    // end scrollBarEasyBottom
    self.scrollBarEasyTop.position = CGPoint(x:20, y:400)
    self.addChild(self.scrollBarEasyTop)
    self.scrollBarEasyTop.yScale = 0.2
    self.origSBETpositionX = self.scrollBarEasyTop.position.x
    // end scrollBarEasyTop
    self.ball.position = CGPoint(x:40, y:293)
    self.addChild(self.ball)
    self.ball.yScale = 0.17
    self.ball.xScale = 0.17
    // end ball
    self.maxSBEBX = self.scrollBarEasyBottom.size.width - self.frame.size.width
    self.maxSBEBX *= -1
    self.maxSBETX = self.scrollBarEasyTop.size.width - self.frame.size.width
    self.maxSBETX *= -1
    //
    self.scoreText.text = "0"
    self.scoreText.fontSize = 60
    self.scoreText.position = CGPoint(x: CGRectGetMidX(self.frame), y: 500)
    self.scoreText.text = String(self.score)
    self.addChild(self.scoreText)
    timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("scoreIncrease") , userInfo: nil, repeats: true)
    func scoreIncrease (){
        score++
        println(score)
    }


}
override func update(currentTime: NSTimeInterval){
    if self.scrollBarEasyBottom.position.x <= maxSBEBX + 1200 {
        self.scrollBarEasyBottom.position.x = self.origSBEBpositionX
    }
    if self.scrollBarEasyTop.position.x <= maxSBETX + 1200 {
        self.scrollBarEasyTop.position.x = self.origSBETpositionX
    }

    scrollBarEasyBottom.position.x -= CGFloat(self.SBEBSpeed)
    scrollBarEasyTop.position.x -= CGFloat(self.SBETSpeed)
    // moving bars
    var degreeRotation = CDouble(self.SBEBSpeed) * M_PI / 180
    self.ball.zRotation -= CGFloat(degreeRotation)
    //rotate ball


    }


    }
Run Code Online (Sandbox Code Playgroud)

运行此代码后,我总是得到一个"无法识别的选择器发送到实例错误".

Moh*_*din 81

你可以使用这样一个:

var timer = NSTimer()

override func viewDidLoad() {
    scheduledTimerWithTimeInterval()
}

func scheduledTimerWithTimeInterval(){
    // Scheduling timer to Call the function "updateCounting" with the interval of 1 seconds
    timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateCounting"), userInfo: nil, repeats: true)
}

func updateCounting(){
    NSLog("counting..")
}
Run Code Online (Sandbox Code Playgroud)

斯威夫特3:

var timer = Timer()

override func viewDidLoad() {               // Use for the app's interface
    scheduledTimerWithTimeInterval()
}

override func didMove(to view: SKView) {    // As part of a game
    scheduledTimerWithTimeInterval()
}

func scheduledTimerWithTimeInterval(){
    // Scheduling timer to Call the function "updateCounting" with the interval of 1 seconds
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.updateCounting), userInfo: nil, repeats: true)
}

@objc func updateCounting(){
    NSLog("counting..")
}
Run Code Online (Sandbox Code Playgroud)

  • timer.invalidate() (13认同)
  • 非常感谢!我有一个问题,我怎么能停止计时器? (2认同)

Sha*_*hiq 30

在swift中有一种叫做NSTimer的东西可以解决你的问题.我给出了一个如何使用它的例子.只需根据您的目的进行定制.

var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, 
                                                   target: self, 
                                                   selector: Selector("yourMethodToCall"), 
                                                   userInfo: nil, 
                                                   repeats: true)
Run Code Online (Sandbox Code Playgroud)

将此行添加到需要重复调​​用函数的位置.

  1. 1.0是指1秒.
  2. 更改selector为调用yourMethodName
  3. repeats设置为true每秒调用该函数.

试试这个,让我知道你是否被困在某个地方.谢谢.

  • 尝试将`scoreIncrease`方法放在`didMoveToView`方法之外. (2认同)

Amr*_*gry 9

斯威夫特3

找到这个适合我的解决方案

weak var timer: Timer?
var timerDispatchSourceTimer : DispatchSourceTimer?

func startTimer() {
    if #available(iOS 10.0, *) {
        timer = Timer.scheduledTimer(withTimeInterval: 3, repeats: true) { [weak self] _ in
            // do something here

        }

    } else {
        // Fallback on earlier versions
        timerDispatchSourceTimer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main)
        timerDispatchSourceTimer?.scheduleRepeating(deadline: .now(), interval: .seconds(60))
        timerDispatchSourceTimer?.setEventHandler{
                // do something here

        }
        timerDispatchSourceTimer?.resume()
    }
}

func stopTimer() {
    timer?.invalidate()
    //timerDispatchSourceTimer?.suspend() // if you want to suspend timer 
    timerDispatchSourceTimer?.cancel()
}

// if appropriate, make sure to stop your timer in `deinit`
deinit {
    stopTimer()
}
Run Code Online (Sandbox Code Playgroud)

  • 在 SpriteKit 中使用 NSTimer 不是基于时间的操作的首选方式。它不考虑节点、场景或视图的暂停状态,并且在某些情况下会导致某些问题。使用 SKActions 或 update: 方法是更好的选择。 (2认同)

Rin*_*cha 9

我更喜欢

var timer: Timer?

override func viewDidLoad() {
    super.viewDidLoad()          

    timer =  Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (timer) in                
        // Do what you need to do repeatedly         
    }
}
Run Code Online (Sandbox Code Playgroud)

要停止它:

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    if timer != nil {
        timer?.invalidate()
        timer = nil
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 8

Xcode 10.2 Swift 5:

override func viewDidLoad() {
    super.viewDidLoad()
    // ...
    Timer.scheduledTimer(timeInterval: 8.0, target: self, selector: Selector(("your @obcj func name")), userInfo: nil, repeats: true)
}

//Anywhere in the same view controller to stop the loop:
Timer.cancelPreviousPerformRequests(withTarget: your @obcj func name())
Run Code Online (Sandbox Code Playgroud)