ios - 使用数组将值传递给 SWIFT 中的 TIMER

标签 ios objective-c arrays swift nstimer

<分区>


已关闭 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/

上一篇:ios - 如何将 alpha 设置为导航栏但子项除外(后退按钮、标题等)?

下一篇:ios - 从右侧推送/呈现一个 View Controller , View Controller 覆盖前一个 View Controller 的 3/4 部分

相关文章:

arrays - 如何使用数组更改多个变量而不是值?

ios - 有没有办法知道 NSURL 是指向远程服务器还是指向用户设备上的 Assets 库?

ios - 如何取消隐藏 UITableView 部分的动画?

iphone - 异步方法、 block 和 GCD,难以理解

arrays - 什么是 "Oracle Access"?

java - 尝试从以前的数组创建 ArrayList<Object> - Java

ios - 如何根据屏幕尺寸更改字体大小

ios - 从设置iOS设置Twitter帐户

ios - 在 MonoTouch 中的 View Controller 之间切换

ios - 在 UIScrollview 中水平显示 pdf 文件