我正在为我的班级制作游戏,我需要帮助制作计时器。我的游戏是一个街机/无尽的游戏,其中有几个需要挖掘的瓷砖,计时器会慢慢变短和缩短。
我想的可能是一个UIProgressView
,从大约1900毫秒左右开始,每次敲击一个瓷砖,它会减少5毫秒左右(起初不是很明显,但它会加起来)直到这个代码
var timerTime :Int = 1900
func timerDecrement() {
if (timerTime => 200) {
timerTime = (timerTime - 5)
//OR
timerTime--
timerTime--
timerTime--
timerTime--
timerTime--
}
}
k,所以使用那些代码或类似的东西,我需要制作一个动画定时器 - 事物(例如,UIProgressView),因为我从来没有使用过计时器,到目前为止,我的实验没有结果。
编辑: 我无法在星期一之前添加代码,因为这就是我学校的工作方式.-。 我试图让我的UIPROGRESSVIEW倒数,但我不理解它是如何工作的。
答案 0 :(得分:0)
我很快创建了这样一个Timer(interval
属性文档中的描述)
使用间隔和回调启动它,当需要更改间隔时,只需通过执行timer.interval -= 5
之类的操作来更改此计时器的interval属性。此外,您需要在某处保留此计时器的参考,否则它将无法正常工作
//
// VarTimer.swift
// VarTimer
//
// Created by Kametrixom on 29.05.15.
// Copyright (c) 2015 Kametrixom Tikara. All rights reserved.
//
import Foundation
class Timer: NSObject {
private var timer : NSTimer?
private var lastTime : UInt64 = 0
var handler : () -> ()
var running : Bool = false {
didSet {
if running != oldValue {
if running {
timer = NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: "update", userInfo: nil, repeats: true)
lastTime = mach_absolute_time()
} else {
timer?.invalidate()
}
}
}
}
/// The time interval for this timer. If this value is changed,
/// the percentage that has been completed of the old interval
/// is scaled to the new one.
///
/// E.g.: Timer with 4 second interval is started, one second
/// later (after a fourth or the time has passed) the interval
/// is changed to 2 seconds, therefore the new timer will fire
/// in 1.5 seconds (because a fourth has already been done with
/// the old interval)
var interval : NSTimeInterval {
didSet {
if interval != oldValue && running {
timer?.invalidate()
let nsec = UInt64(oldValue * Double(NSEC_PER_SEC))
let percentDone = Double(mach_absolute_time() - lastTime) / Double(nsec)
let fireDateShift = (1 - percentDone) * interval
let fireDate = NSDate().dateByAddingTimeInterval(fireDateShift)
timer = NSTimer(fireDate: fireDate, interval: interval, target: self, selector: "update", userInfo: nil, repeats: true)
NSRunLoop.mainRunLoop().addTimer(timer!, forMode: NSRunLoopCommonModes)
lastTime = mach_absolute_time()
}
}
}
convenience init(interval: NSTimeInterval) {
self.init(interval: interval, handler: {})
}
init(interval: NSTimeInterval, handler: () -> ()) {
self.interval = interval
self.handler = handler
super.init()
}
func start() {
running = true
}
func stop() {
running = false
}
func update() {
lastTime = mach_absolute_time()
handler()
}
deinit {
timer?.invalidate()
}
}