Loading [MathJax]/jax/output/CommonHTML/config.js
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >在swift中创建秒表

在swift中创建秒表
EN

Stack Overflow用户
提问于 2017-06-24 00:55:21
回答 3查看 7.2K关注 0票数 2

我尝试过搜索其他答案,但找不到适用于我的方案的答案。我正在用swift编写一个游戏,并想创建一个秒表来确定玩家玩多长时间。当用户按下时,秒表将启动,当某个动作发生时,计时器停止并重置。我想使用分钟、秒、毫秒(例如00:00.00)。

目前,时间函数是可行的。它不是从0开始的,它是从当前的秒数开始的(我知道这是什么时候开始的,但我不知道如何从0开始)。它也只在我触摸屏幕时更新,我需要它从00:00.00开始计数,并自动更新,直到触发取消操作。

谢谢您抽时间见我。

这是我到目前为止所知道的:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
class GameScene: SKScene {

var activeTimer = SKLabelNode()
//var bestTime = SKLabelNode()

var startTime = TimeInterval()
//var currentTime = TimeInterval()
//var countingTime = TimeInterval()
var updateTimerAction = SKAction()


override func didMove(to view: SKView) {

    activeTimer = self.childNode(withName: "active_timer") as! SKLabelNode
    //bestTime = self.childNode(withName: "best_time") as! SKLabelNode

    startTime = TimeInterval(Calendar.current.component(.second, from:Date()))
    updateTimerAction = SKAction.sequence([SKAction.run(updateTimer), SKAction.wait(forDuration: 1.0)])
}


func startGame() {
    // Other code
    startGameTimer()
}

func resetGame() {
    // Other code
    stopGameTimer()
}

func startGameTimer() {
    run(SKAction.repeatForever(updateTimerAction), withKey: "timer")
}

func updateTimer() {
    activeTimer.text = stringFromTimeInterval(interval: startTime) as String
}

func stringFromTimeInterval(interval: TimeInterval) -> NSString {

    let ti = NSInteger(interval)

    let ms = Int((interval.truncatingRemainder(dividingBy: 1)) * 1000)

    let seconds = ti % 60
    let minutes = (ti / 60) % 60

    return NSString(format: "%0.2d:%0.2d.%0.2d",minutes,seconds,ms)
}


func stopGameTimer() {
    removeAction(forKey: "timer")
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    startGame()

    for touch in touches {
        // other code
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

    for touch in touches {
        // other code
    }
}


override func update(_ currentTime: TimeInterval) {

    updateTimer()

    if <action>  {
        // stop timer and reset game
        resetGame()
    }
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-06-24 01:05:01

与使用TimeInterval对象相比,使用Timer对象可能更好,该对象调用一个函数,该函数在每隔1秒(或者可以更短)之后相应地从0开始递增标签(或内部变量)的值。为了停止时钟,只需调用Timer对象的invalidate函数即可。有关更多信息,请查看文档:https://developer.apple.com/documentation/foundation/timer

票数 2
EN

Stack Overflow用户

发布于 2017-06-24 23:37:26

下面几行代码来自一个实际的macOS游戏,这是我在大约3周前提交给Mac App Store的。它将一个数字倒数到0。在您的情况下,更改

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
self.currentSeconds -= 1

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
self.currentSeconds += 1

timeBackNode是一个包含SKLabelNode对象timeNode0和timeNode1的空节点。因此,在使用didMove开始游戏时创建它。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
var currentSeconds = Int() // currentSeconds
var timeNode0 = SKLabelNode() // timeNode0
var timeNode1 = SKLabelNode() // timeNode1
func setupTimeGoal() {
    enumerateChildNodes(withName: "//TimerBack", using: { timeBackNode, _ in
        let goal = self.timeDict["num"] as! Int
        self.currentSeconds = goal // In your case, goal is 0 since you are going to count up.
        self.timeNode0 = SKLabelNode(fontNamed: "Your font's font name")
        self.timeNode0.text = self.makeTimeWithSeconds(secs: goal)
        self.timeNode0.fontSize = 26
        self.timeNode0.fontColor = SKColor.black
        self.timeNode0.horizontalAlignmentMode = .center
        self.timeNode0.position = CGPoint(x: 1, y: -22)
        timeBackNode.addChild(self.timeNode0)

        self.timeNode1 = SKLabelNode(fontNamed: "Your font's font name")
        self.timeNode1.text = self.makeTimeWithSeconds(secs: goal) // this function translate a counting number into a time code like 00:00:00
        self.timeNode1.fontSize = 26
        self.timeNode1.fontColor = SKColor.cyan
        self.timeNode1.horizontalAlignmentMode = .center
        self.timeNode1.position = CGPoint(x: 0, y: -23)
        timeBackNode.addChild(self.timeNode1)
    })
}

func repeatTime() {
    let waitAction = SKAction.wait(forDuration: 1.0)
    let completionAction = SKAction.run {
        if self.currentSeconds == 0 && self.gameState == .playing {
            self.removeAction(forKey: "RepeatTime")
            self.proceedLoss()
            return
        }
        self.currentSeconds -= 1
        self.timeNode0.text = self.makeTimeWithSeconds(secs: self.currentSeconds)
        self.timeNode1.text = self.makeTimeWithSeconds(secs: self.currentSeconds)
    }
    let seqAction = SKAction.sequence([waitAction, completionAction])
    let repeatAction = SKAction.repeatForever(seqAction)
    self.run(repeatAction, withKey: "RepeatTime")
}
票数 2
EN

Stack Overflow用户

发布于 2017-07-02 19:36:15

这就是我最终要做的事情。虽然El Tomato的答案似乎有效,但考虑到我的代码设置,我走了一条略有不同的路线。在与其他一些朋友交谈后,由于我的应用程序的设计,我选择使用计时器。如果我碰巧在使用Timer对象时遇到任何问题,我会更新这个问题。

下面的代码将在触摸时启动,以"00:00.00“的格式更新,并在操作触发时停止。此时间将暂停,直到下一次触摸,然后计时器将从零开始。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
class GameScene: SKScene {

var seconds = 0
var timer = Timer()
var timeStarted = Bool()
var activeTimer = SKLabelNode()
//var bestTime = SKLabelNode()

override func didMove(to view: SKView) {

    activeTimer = self.childNode(withName: "active_timer") as! SKLabelNode
    //bestTime = self.childNode(withName: "best_time") as! SKLabelNode
    timeStarted = false

}

func startGame() {

    startGameTimer()
    timeStarted = true
}

func resetGame() {

    timeStarted = false
    stopGameTimer()
    seconds = 0
}

func startGameTimer() {
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(updateTimer)), userInfo: nil, repeats: true)
}

func updateTimer() {
    seconds += 1
    activeTimer.text = timeString(time: TimeInterval(seconds))
}

func timeString(time:TimeInterval) -> String {
    let hours = Int(time) / 3600
    let minutes = Int(time) / 60 % 60
    let seconds = Int(time) % 60
    return String(format:"%02i:%02i.%02i", hours, minutes, seconds)
}


func stopGameTimer() {
    timer.invalidate()
    removeAction(forKey: "timer")
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    if !timeStarted {
        startGame()
    }

    for touch in touches {
        // other code
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

    for touch in touches {
        // other code
    }
}


override func update(_ currentTime: TimeInterval) {

    if timeStarted {
        updateTimer()
    }

    if <action>  {
    // stop timer and reset game
    resetGame()
    }
}
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44731739

复制
相关文章
Fedora 运行 Apache 的时候无法启动,提示日志错误
什么是 SELinux 呢?其实他是『 Security Enhanced Linux 』的缩写,字面上的意义就是安全强化的 Linux 之意!
HoneyMoose
2020/05/20
8270
错误:org.apache.jasper.JasperException 无法为JSP编译类
在tomcat的安装路径找到web.xml,修改org.apache.jasper.servlet.JspServlet里的配置;
全栈程序员站长
2022/07/25
4.2K0
Mac安装OpenCV3 --with-contrib的错误处理
在Mac中安装OpenCV3时,如果需要安装--with-contrib,则会报错,OpenCV 3的安装命令为:
Tyan
2019/05/25
8360
eclipse500错误原因解决方法_eclipse运行无法显示网页
eclipse内部浏览器报错:此错误(HTTP 500 内部服务器错误)意味着您正在访问的网站出现了服务器问题,此问题阻止了该网页的显示
全栈程序员站长
2022/09/22
3.3K0
eclipse500错误原因解决方法_eclipse运行无法显示网页
目标检测第3步-模型训练
本文在学习《Tensorflow object detection API 搭建属于自己的物体识别模型(2)——训练并使用自己的模型》的基础上优化并总结,此博客链接:https://blog.csdn.net/dy_guox/article/details/79111949,感谢此博客作者。
潇洒坤
2018/12/21
1.7K3
pycharm无法运行问题[通俗易懂]
解决方法 一、在右上角点击configure Pycharm interpreters
全栈程序员站长
2022/09/27
2.4K0
pycharm无法运行问题[通俗易懂]
【错误记录】Android 应用连接 BLE 设备无法读取数据 ( 可以写出数据 | 无法读取数据 )
发送数据成功 : Android 应用 向 BLE 硬件设备发送数据 , 成功 ;
韩曙亮
2023/03/28
1.6K0
windows无法连接到打印机错误为0x000000011b_无法连接到打印机错误0000011b
最近打印机连不上,查了下网上的资料,发现是Windows10的一个更新bug导致,但是按照网上的方法视乎重启后windows会强制更新,还是无法彻底解决问题。于是在继续查找到相关资料,现在将解决方法记录下来。
全栈程序员站长
2022/09/30
3.6K0
windows无法连接到打印机错误为0x000000011b_无法连接到打印机错误0000011b
NodeJS 导入包的时候出现的 @types 错误导致程序无法运行
在一次开发 NodeJS 项目的时候,我们希望包的导入是用 import 导入的方式。
HoneyMoose
2021/11/10
1.7K0
NodeJS 导入包的时候出现的 @types 错误导致程序无法运行
Java命令行运行错误: 找不到或无法加载主类
本部分将针对在“一”中提出的两个问题发生原因,分别进行分析及处理。并且会介绍java的一些和处理问题相关的基本概念。
全栈程序员站长
2022/09/19
10.2K0
Java命令行运行错误: 找不到或无法加载主类
cmd下运行java程序报错:错误: 找不到或无法加载主类
通常出现这种问题有以下三种原因: 第一:环境变量配置不正确,配置环境变量时一定要将CLASSPATH配上,(配置教程) 第二:执行方法有误,进入java文件目录下,首先执行javac xxx.java,生成一个xxx.class文件,然后执行java xxx 第三:程序有问题,比如我之前直接在cmd下执行eclipse下的java文件,始终报“错误: 找不到或无法加载主类”这个异常,但是在eclipse下执行同一个文件却没有问题,后来仔细发现原来是java文件中的包名导致的,删除掉红色框中的内容即可正常运行。这是在编译通过的情况下执行编译后的文件出现的问题,如果编译都没通过那就是java文件的问题,仔细检查一下文件是否有异常,比如类没有被public修饰,或者main方法没有static修饰等等。
我是李超人
2020/08/21
7.7K0
cmd下运行java程序报错:错误: 找不到或无法加载主类
win10打印服务无法启动(运行时错误automation)
这是3/11号遇到的问题,微软更新了一个叫KB5009543的补丁之后,电脑的打印功能就一直打印不了,刚开始检查以为打印机脱机或者驱动没安装,检查之后发现毫无作用,还是提示操作无法完成。到电脑控制面板-打印机设备查看所有连接过的打印机都是灰色的。
全栈程序员站长
2022/08/02
2.1K0
win10打印服务无法启动(运行时错误automation)
出现“内部错误,无法显示”
This page contains the following errors: error on line 2 at column 6: XML declaration allowed only at the start of the document Below is a rendering of the page up to the first error. 提示信息是头部有错误,我登录后台查看我修改过的页面,然后找到home.php我看了十几分钟没有发现那里有错误~~ 莫非头部不能有空格? 去掉试试
苦咖啡
2018/05/07
3.2K0
tensorflow对象检测框架训练VOC数据集常见的两个问题
Tensorflow自从发布了object detection API这套对象检测框架以来,成为很多做图像检测与对象识别开发者手中的神兵利器,因为他不需要写一行代码,就可以帮助开发者训练出一个很好的自定义对象检测器(前提是有很多标注数据)。我之前曾经写过几篇文章详细介绍了tensorflow对象检测框架的安装与使用,感兴趣可以看如下几篇文章!
OpenCV学堂
2019/04/29
2.1K2
tensorflow对象检测框架训练VOC数据集常见的两个问题
tf.contrib.image
该模块提供图像处理功能;目前支持YIQ空间的色度变换(包括饱和度和色调的变化)和投影变换(包括旋转)。
狼啸风云
2019/08/31
1.3K0
tf.contrib.eager
EXPERIMENTAL: APIs here are unstable and likely to change without notice.
狼啸风云
2022/06/05
2290
tf.contrib.summary
The operations in this package are safe to use with eager execution turned on or off. It has a more flexible API that allows summaries to be written directly from ops to places other than event log files, rather than propagating protos from tf.summary.merge_all to tf.summary.FileWriter.
狼啸风云
2022/06/05
2560
tensorflow编程: Layers (contrib)
min(max(features, 0), 6)。即对 tf.nn.relu 的优化,防止 relu过后 某些 极端值 依然 大于6
JNingWei
2018/09/28
7970
Gamemaker Studio运行时弹出打开窗口导致无法启动的错误
突然有个游戏灵感,看了一下 Unity 3D 好像和预期效果有些偏差,多处辗转于不同语言和引擎,最终决定使用 GameMaker Studio
szhshp
2022/08/15
1.2K0
Gamemaker Studio运行时弹出打开窗口导致无法启动的错误
porm导致项目运行错误
由于创建moduel基于原来项目之上导致porm会继承原有项目导致运行错误 解决:删除继承关系 relative
全栈程序员站长
2022/07/02
8550
porm导致项目运行错误

相似问题

model_main.py无法训练移动网络ssd v2 - tensorflow对象检测api

11

运行train.py或model_main.py时出现未知错误

253

tensorflow.contrib.learn.Estimator负荷训练模型

12

无法为tesseract创建训练数据(mac os x)

22

Sinatra错误:无法激活sinatra-contrib-1.4.2

25
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文