<分区>
编辑问题以包含 desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem 。这将有助于其他人回答问题。
已关闭 8 年前。
<分区>
编辑问题以包含 desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem 。这将有助于其他人回答问题。
已关闭 8 年前。
我有一个工作倒计时,您可以通过按添加按钮来增加它,这就是时间倒计时(所以基本上用户可以设置倒计时)
我想将开始时间显示为 00:00,就像我的标签中那样。
当我点击按钮增加倒计时时,它显然从 1 开始,因为目前它只是一个 Int
我可以创建一个数组并增加各个索引,然后将它们显示在我的标签中吗?
任何人都可以帮忙解决这个问题,或者从下面的内容中指出我的编写代码方向吗 谢谢
var timeArray: [Double : Double] = [00, 00]
var timer = NSTimer()
var countdown = 0
func runTimer() {
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self,
selector:Selector("updateTimer"), userInfo: nil, repeats: true)
}
func updateTimer() {
if countdown > 0 {
countdown--
TimerLabel.text = String(countdown)
} else {
countdown = 0
TimerLabel.text = String(countdown)
}
}
@IBOutlet weak var TimerLabel: UILabel!
@IBAction func IncreaseCountdown(sender: AnyObject) {
countdown++
TimerLabel.text = String(countdown)
}
@IBAction func StartCountdown(sender: AnyObject) {
runTimer()
}
@IBAction func StopCountdown(sender: AnyObject) {
timer.invalidate()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
最佳答案
timeArray
的语法是创建一个Dictionary
而不是Array
。我还建议您使用 Int
而不是 Double
:
var timeArray:[Int] = [0, 0]
为您的文本字段创建标签:
// This format will create a string with 2 digits for minute and second with
// a leading 0 for each if needed like "00:00"
TimerLabel.text = String(format: "%02d:%02d", timeArray[0], timeArray[1])
创建计时器时,将时间数组转换回简单的倒计时:
let countdown = timeArray[0] * 60 + timeArray[1]
一种完全不同的可行方法是在内部将您的时间存储为整数秒,并将其显示为分钟和秒。
let countdown = 100 // 1 minute, 40 seconds
TimerLabel.text = String(format: "%02d:%02d", countdown/60, countdown%60)
关于ios - 使用数组将值传递给 SWIFT 中的 TIMER,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27013433/