首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何让一个函数在swift中每秒执行一次?

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

Stack Overflow用户
提问于 2015-05-07 09:16:34
回答 7查看 88.6K关注 0票数 63

我想在我正在工作的游戏中在我的场景的顶部添加一个分数。分数将基于你持续的时间,并且每秒都会增加。提前感谢您的帮助!

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
    }        
}

在运行这段代码之后,我总是得到一个

发送到实例错误的

无法识别的选择器

EN

回答 7

Stack Overflow用户

发布于 2015-05-07 16:05:06

您可以像这样使用一个:

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..")
}

Swift 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..")
}

Swift 5:

注意:此解决方案与iOS 10.0+兼容。

// If needing to check for iOS compatibility use
// if #available(iOS 10.0, *) {code}

var timer = Timer()

override func viewDidLoad() {
    self.timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { _ in
        updateCounting()
    })
}

func updateCounting(){
    print("counting...")
}

然后,您可以使用以下命令使计时器无效(停止):

timer.invalidate()
票数 99
EN

Stack Overflow用户

发布于 2015-05-07 09:25:33

在swift中有一个叫做NSTimer的东西可以解决你的问题。我已经给出了一个例子,比如你可以如何使用它。只需根据您的目的进行自定义即可。

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

将这一行添加到需要重复调用函数的位置。

  1. 1.0指的是1秒。将call yourMethodName
  2. repeatsselector更改为true以每秒调用该函数。

试试这个,如果你卡在什么地方了,请告诉我。谢谢。

票数 33
EN

Stack Overflow用户

发布于 2017-02-23 23:40:04

Swift 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()
}
票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30090309

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档