【问题标题】:use an array to pass values into a TIMER IN SWIFT [closed]使用数组将值传递到 TIMER IN SWIFT [关闭]
【发布时间】:2014-11-19 09:39:20
【问题描述】:

我有一个工作倒计时,您可以通过按下添加按钮来增加倒计时,这就是倒计时的时间(所以基本上用户可以设置倒计时)

我想将开始时间显示为 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.
   }


}

【问题讨论】:

    标签: ios objective-c arrays swift nstimer


    【解决方案1】:

    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)
    

    【讨论】:

    • 好东西,试试看,谢谢你的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    • 2012-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多