我已将日期选择器设置为文本字段的输入视图。日期选择器的最小日期和间隔分钟为15.现在它给出了更改值更改委托中的旋转的正确日期。但是如果我没有旋转选择器并点击完成按钮并且首先选择默认值,则它仅提供当前日期。我希望它能给我一个默认显示在选择器中的日期。这是代码:
class ViewController: UIViewController {
@IBOutlet weak var timeField: UITextField!
var datePicker:UIDatePicker!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func CallPicker(sender: UITextField) {
let datePickerView:UIDatePicker = UIDatePicker()
datePickerView.datePickerMode = UIDatePickerMode.DateAndTime
datePickerView.minuteInterval = 15
datePickerView.minimumDate = NSDate()
datePicker = datePickerView
let toolBar = UIToolbar()
toolBar.sizeToFit()
let spaceButton = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
let doneButton = UIBarButtonItem(title: "Done", style: .Plain, target: self, action: "doneTapped")
toolBar.setItems([spaceButton, doneButton], animated: false)
toolBar.userInteractionEnabled = true
sender.inputView = datePickerView
sender.inputAccessoryView = toolBar
datePickerView.addTarget(self, action: Selector("datePickerValueChanged:"), forControlEvents: UIControlEvents.ValueChanged)
}
func doneTapped() {
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .MediumStyle
dateFormatter.timeStyle = .MediumStyle
timeField.text = dateFormatter.stringFromDate(datePicker.date)
timeField.resignFirstResponder()
}
func datePickerValueChanged(sender: UIDatePicker) {
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .MediumStyle
dateFormatter.timeStyle = .MediumStyle
timeField.text = dateFormatter.stringFromDate(sender.date)
}
}
场景:现在假设它的8:42。日期选择器将显示8:30作为第一个条目,但是当我点击完成按钮时,它将仅提供当前时间8:42。然而,如果我滚动旋转并返回第一个条目,它的效果会很好。
答案 0 :(得分:0)
选择日期后,请尝试使用以下代码
let userDateFormate = NSDateFormatter()
userDateFormate.dateFormat = "MMMM dd, yyyy"
let dateString = userDateFormate.stringFromDate(date)
dateFormate.dateFormat = "MMMM dd, yyyy"
dateFormate.timeZone = NSTimeZone.init(forSecondsFromGMT: 0)
let dateValue = dateFormate.dateFromString(dateString)
答案 1 :(得分:0)
我也面临同样的问题,解决方法是在Calender.current.dateComponents的帮助下为UIDatePicker设置一个较晚的时间。
func patchTime(){
var components = Calendar.current.dateComponents([.hour, .minute], from: self.timePicker.date);
components.hour = (components.hour ?? 0) + 1
components.minute = 0
let calendar = Calendar.current
let date = calendar.date(from: components)
self.timePicker.date = date!;
}
当前我用于时间选择器,但如果还需要日期,则模式将相同
答案 2 :(得分:-1)
你只需要将datePicker的date属性从当前日期设置为custom,然后就可以了。