如何在 Swift 中为日期选择器设置特定的默认时间 [英] How to set a specific default time for a date picker in Swift
问题描述
有没有办法设置日期选择器来显示特定的加载时间?我使用 GitHub 中弹出的 UIAlertView 中的 squimer/datePickerDialog 子类从开始时间、结束时间、开始日期和结束日期的四个文本字段启动了四个日期选择器实例.
Is there any way to set a date picker to display a specific time on load? I have four date picker instances initiated from four text fields for Start Time, Finish Time, Start Date and Finish Date using the squimer/datePickerDialog subclass from GitHub that pops up in a UIAlertView.
在我的应用中,默认开始时间是早上 7:00,默认结束时间是下午 5:00,让用户根据这些时间进行调整.
In my app a default start time would be 7:00 AM and a default finish time would be 5:00 PM and let the user adjust around those times.
我能看到的是,您可以将 datePicker.defaultDate 设置为 currentDate、minimumDate 或 maximumDate,并且只能设置一次.是否可以在我从 ViewController 的调用中将 defaultDate 设置为 sTime = "07:00" 和 fTime = "17:00" 的硬编码字符串?
All I can see is that you can set the datePicker.defaultDate to currentDate, minimumDate or maximumDate and only once. Is it possible set the defaultDate to hardcoded strings of sTime = "07:00" and fTime = "17:00" in my calls from the ViewController?
任何帮助将不胜感激.
这就是我从 viewController 调用子类的方式
This is how I am calling the subclass from my viewController
@IBAction func setFT(sender: UITextField) {
resignKeyboardCompletely(sender)
DatePickerDialog().show("Pick a Finish Time", doneButtonTitle: "Done", cancelButtonTitle: "Cancel", datePickerMode: .Time) {
(timeFinish) -> Void in
self.dateFormatter.dateFormat = "HH:mm"
let finTime = self.dateFormatter.stringFromDate(timeFinish)
self.finishTime.text = finTime
}
defaults.setObject(finishTime.text, forKey: "finishTime")
print(finishTime.text)
}
请注意,在整个过程中,我也试图通过 NSUser Defaults 来保持持久性.
Note that throughout this I am also trying to maintain persistence through NSUser Defaults.
推荐答案
您是否正在寻找通过字符串设置时间.如果是这种情况,您可以使用这样的日期格式化程序.
Are you looking for setting the time through a string. If that''s the case you can use a date formatter like this.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm"
let date = dateFormatter.dateFromString("17:00")
datePicker.date = date
向 Picker 类
init(time:String) {
super.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height))
setupView()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm"
if let date = dateFormatter.dateFromString("17:00") {
datePicker.date = date
}
}
这篇关于如何在 Swift 中为日期选择器设置特定的默认时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!