我正在使用下面的代码来了解日期选择器。它有效,但奇怪的是当我第一次滚动日期选择器时,预期的变化不会发生。之后它会正常工作。不知道发生了什么。
import UIKit
import Foundation
class ViewController: UIViewController {
// Place this code inside your ViewController or where you want ;)
var txtField: UITextField = UITextField(frame: CGRect(x: 100, y: 0, width: 300, height: 50))
override func viewDidLoad() {
super.viewDidLoad()
// date picker setup
let datePickerView:UIDatePicker = UIDatePicker()
// choose the mode you want
// other options are: DateAndTime, Time, CountDownTimer
datePickerView.datePickerMode = UIDatePickerMode.countDownTimer
// choose your locale or leave the default (system)
//datePickerView.locale = NSLocale.init(localeIdentifier: "it_IT")
datePickerView.addTarget(self, action: #selector(onDatePickerValueChanged(_:)), for: UIControlEvents.valueChanged)
txtField.inputView = datePickerView
// datepicker toolbar setup
let toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.default
toolBar.isTranslucent = true
let space = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.done, target: self, action: #selector(ViewController.doneDatePickerPressed))
// if you remove the space element, the "done" button will be left aligned
// you can add more items if you want
toolBar.setItems([space, doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
toolBar.sizeToFit()
txtField.inputAccessoryView = toolBar
self.view.addSubview(txtField)
}
func doneDatePickerPressed(){
self.view.endEditing(true)
}
func onDatePickerValueChanged(_ sender: UIDatePicker) {
let (h, m, _) = secondsToHoursMinutesSeconds (duration: sender.countDownDuration)
self.txtField.text = String("\(h) Hours \(m) Minutes")
}
func secondsToHoursMinutesSeconds (duration : Double) -> (Int, Int, Int) {
let seconds:Int = Int(duration)
return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
}
}