kenny10009 kenny10009 - 1 month ago 17
iOS Question

Grabbing time from UIDatePicker

New to Swift so bare with me for a second. I wanted to know how it it possible to grab the time from a UIDatePicker in Count Down Timer mode, and then display that while counting down in a Hour:Minute:Second format. My biggest issue is actually grabbing the time from the Date Picker. As I'm not really to sure how to start that.

override func viewDidLoad() {
super.viewDidLoad()

stopWatchPicker.countDownDuration = 60.0;

if timerCount == 0 {
timerRunning = false
}
}

var timerCount = 60 //set to 60 for testing purposes
var timer = Timer()
var timerRunning = false


@IBOutlet weak var stopWatchPicker: UIDatePicker!
@IBOutlet weak var countDownLabel: UILabel!

@IBAction func startButton(_ sender: AnyObject) {
if timerRunning == false {
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
timerRunning = true
}
}
@IBAction func stopButton(_ sender: AnyObject) {
timer.invalidate()
timerRunning = false
}

func updateCounter() {
timerCount -= 1
countDownLabel.text = "\(timerCount)"

if timerCount == 0 {
timer.invalidate()
timerRunning = false
}
}

Answer

You need to grab the countDownDuration from the stopWatchPicker and assign it to the timerCount variable.

@IBAction func startButton(_ sender: AnyObject) {
  if timerRunning == false {
    timerCount = stopWatchPicker.countDownDuration
    timerRunning = true
    timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
  }
}

Cheers!