Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        5年前关闭。
                                                                                            
                
        
我有一个有效的倒计时,您可以通过按添加按钮来增加倒数,这就是倒数的时间(因此用户基本上可以设置倒数)

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

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

如何创建数组并增加单个索引,然后在标签中显示它们?

任何人都可以帮忙解决这个问题,或者从下面的内容中指出我的编写代码方向
谢谢

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 - 使用数组将值传递到TIMER IN SWIFT中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27013433/

10-11 23:06
查看更多