ios - 在 SWIFT 倒计时中使用的访问字典

标签 ios objective-c dictionary swift timer

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

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

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

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

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

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

这是我的倒计时完整代码

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.
    }


}

最佳答案

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

@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,因为约定是变量应以小写字母开头

关于ios - 在 SWIFT 倒计时中使用的访问字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27006370/

相关文章:

ios - 在 viewController 中实例化时如何设置 UIImageView 的大小/框架和 contentMode?

objective-c - 使用 NSViewController 导入 Nib 文件时,文字看起来不流畅

objective-c - 设置类(class)的区别?

ios - NSInvalidUnarchiveOperationException,UIStoryboardShowSegueTemplate

ios - 在离线模式下播放 youtube 视频?

ios - 传递 NSArray 使数组为空

ios - 使用 Core Text 布置单个字形

c# - 多个列表或字典?

python - 在 Python 中合并两个对象

java - 为什么 java.util.Map 值可以是原始数组而不是单个原始值