Home > Back-end >  How to get initial value of datePicker Swift
How to get initial value of datePicker Swift

Time:04-09

I want to get initial value of timePicker, value changes when I am just scrolling time. Please watch photos it will be more clear to understand what I want.

https://imgur.com/a/3Hg69uR

@IBAction func datePickerChanged(_ sender: Any) {
    let dateFormatter = DateFormatter()
    dateFormatter.timeStyle = .short
    dateFormatter.dateFormat = "HH:mm"
    let strDate = dateFormatter.string(from: datePicker.date)
    datePickerLb.text = strDate
}

CodePudding user response:

All you need is to update the label inside your viewDidLoad method. I would move the date formatter declaration out of that method to avoid creating a new one every time the value changes. Note that you should use timeStyle or dateFormat but not both. When displaying dates to the end user you should always respect the devices locale and settings so you should choose timeStyle in this case:


let dateFormatter: DateFormatter = {
    let dateFormatter = DateFormatter()
    dateFormatter.timeStyle = .short
    return dateFormatter
}()

override func viewDidLoad() {
    super.viewDidLoad()
    // your code

    // you can update the label here
    // datePickerLb.text = dateFormatter.string(from: datePicker.date)
    // or manually send the valueChanged action to force the update at view did load
    datePicker.sendActions(for: .valueChanged)
}

@IBAction func datePickerChanged(_ datePicker: UIDatePicker) {
    datePickerLb.text = dateFormatter.string(from: datePicker.date)
}

CodePudding user response:

The answer by @Leo is practical. One thing to add is that if you wanted the date updated while picker it is rolling then, unfortunately, it is impossible with UIDatePicker itself. This is because UIDatePicker is not a subclass of UIPickerView and it manages a UIPickerView internally. The the solution here might be use a custom UIPickerView. Then for that UIPickerView you can implement it's delegate method like this:

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

switch component {
case 0:
    currentTime.hours = pickerView.selectedRow(inComponent: 0)
    return "\(row) Hour"
case 1:
    currentTime.minutes = pickerView.selectedRow(inComponent: 1)
    return "\(row) Minute"
case 2:
    currentTime.seconds = pickerView.selectedRow(inComponent: 2)
    return "\(row) Second"
default:
    return ""

}

}

currentTime var should, for example, have a didSet to update some view elements when it changes.

  • Related