我可以从一个数字创建一个倒数,在这种情况下为5,它运作良好。但是我怎么能在标签上加上日期选择器的日期并从中倒数呢?
1-我想我可以在日期选择器中获取所选日期。
let wakeUpTime = datePicker.date
2-下一步是把它放在“countingLabel”中,这是我无法解决的下一个问题。当然,这不起作用:
countingLabel.text = String(wakeUpTime)
所以,我的问题是:如何将日期选择器的日期放在标签上并从中倒数?
这是完整的代码:
var timer = NSTimer()
var counter = 5
@IBOutlet var countingLabel: UILabel!
@IBOutlet weak var datePicker: UIDatePicker!
@IBAction func start(sender: AnyObject) {
// grab the selected date from the date picker
let wakeUpTime = datePicker.date
// count down
timer = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: Selector("updateCounter"), userInfo: nil, repeats: true)
}
func updateCounter() {
countingLabel.text = String(counter--)
}
答案 0 :(得分:3)
您可以使用timeIntervalSinceNow查找日期选择日期与当前时间之间的时间间隔。
func updateCounter() {
let timeLeft = datePicker.date.timeIntervalSinceNow
countingLabel.text = timeLeft.time
}
只需将此扩展程序添加到视图控制器的底部,即可将时间间隔转换为小时分钟和秒数
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var countingLabel: UILabel!
@IBOutlet weak var datePicker: UIDatePicker!
var timer = NSTimer()
override func viewDidLoad() {
super.viewDidLoad()
timer = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: "updateCounter", userInfo: nil, repeats: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func updateCounter() {
let timeLeft = datePicker.date.timeIntervalSinceNow
countingLabel.text = timeLeft.time
}
}
extension NSTimeInterval {
var time:String {
return String(format:"%02dd %02dh %02dm %02ds", Int((self/86400)), Int((self/3600.0)%24), Int((self/60.0)%60), Int((self)%60))
}
}
答案 1 :(得分:1)
使用NSDateFormatter:
let formatter = NSDateFormatter()
formatter.dateFormat = NSDateFormatter.dateFormatFromTemplate("MM.dd.yyyy", options: 0, locale: NSLocale(localeIdentifier: "en-US"))
countingLabel.text = formatter.stringFromDate(date)
date
从Datepicker中保存您的NSDate。
将目标添加到DatePicker,这是在Picker更改其值时调用的方法:
datePicker.addTarget(self, action: Selector("datePickerChanged:"), forControlEvents: .ValueChanged)
您必须在ViewController中实现方法func datePickerChanged(sender: UIDatePicker!)
才能使其正常工作
倒计时部分
添加或减去NSDate wirh .dateByAddingTimeInterval()
例如,减去一天:
var newDate = currentDate.dateByAddingTimeInterval(-1*24*60*60))