访问SWIFT中倒计时内使用的字典

时间:2014-11-18 23:45:56

标签: ios objective-c dictionary swift timer

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

我想将开始时间显示为00:00,就像我的标签一样。

当我点击按钮增加倒计时时,它显然从1开始,因为此时它只是一个Int

所以我想到创建一个像这样的词典

var timeDictionary : [Double : Double] = [00 : 00]

我只想按下+按钮并从00:00开始增加到00:01,2,3。如果可能的话,有人可以帮忙吗?

这是我倒计时的完整代码

var timeDictionary : [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.
    }


}

1 个答案:

答案 0 :(得分:1)

最简单的方法就是在显示计数器时格式化计数器 -

@IBOutlet weak var timerLabel: UILabel!

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 < 1 {
        timer.invalidate()
        countdown=0;
    }

    self.updateTimerLabel();    
}  

@IBAction func IncreaseCountdown(sender: AnyObject) {
    countdown++
    self.updateTimerLabel()
}


@IBAction func StartCountdown(sender: AnyObject) {
    runTimer()
}


@IBAction func StopCountdown(sender: AnyObject) {
    timer.invalidate()
}

func updateTimerLabel() {

    TimerLabel.text =NSString(format:"%02d:%02d",seconds/60,seconds%60)
}

}

请注意,我还将TimerLabel更改为timerLabel,因为约定是变量应以小写字母开头