我正在尝试保存我所拥有的某些UIDatePickers的选定时间。我的日期选择器名为datePicker1。它目前设置为小时和分钟我有一个“保存”按钮,我想保存datePickers时间(小时和分钟),并能够稍后回拨这些时间。我目前正在使用NSUserDefaults,但如果有更好的方法,请告诉我。 (日期与它无关,我正在创建一个应用程序,每天都会给用户一个通知,所以我关心的是小时和分钟计数)。任何帮助将不胜感激。
答案 0 :(得分:0)
如果您想将小时和分钟保存为字符串,这可能会给您一些想法。此实现涉及到单个UIDatePicker的插座和附加到“保存”按钮的操作:
class ViewController: UIViewController {
@IBOutlet weak var datePicker: UIDatePicker!
@IBAction func save(sender: UIButton) {
let dateOnPicker = datePicker.date //capture the date shown on the picker
let dateFormatter = NSDateFormatter() //create a date formatter
//if you want to convert time to string like "9:07 PM":
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle //check out docs for NSDateFormatterStyle to see other styles
let timeAsString = dateFormatter.stringFromDate(dateOnPicker)
print(timeAsString) //ex. prints 3:04 AM as "3:04 AM" and 11:37 PM as "11:37 PM"
//if you want to convert time to string like "0627" (military time):
dateFormatter.dateFormat = "HHmm" //could also store as HH:mm if you want a colon in the string
let timeAsStringMilitaryTime = dateFormatter.stringFromDate(dateOnPicker)
print(timeAsStringMilitaryTime) //in miliatary time: ex. prints 3:04AM as "0304" and 11:37 PM as "2337"
//there are other options, but these are two that you might find useful!
//you could then save either version (whichever you end up using) to NSUserDefaults as a string; i went with the military time version since i think it's easier to parse, but just personal preference:
NSUserDefaults.standardUserDefaults().setObject(timeAsStringMilitaryTime, forKey: "SavedTime")
}
override func viewDidLoad() {
super.viewDidLoad()
//when you start up (or whenever you want to retrieve the saved time), you could check to see if you have a time saved, and if so, parse it into hours and minutes (assuming you are saving the military time version):
if let savedTime = NSUserDefaults.standardUserDefaults().objectForKey("SavedTime") as? String {
//the "HHmm" military time format will ALWAYS be 4 digits long, and the first two characters represent the hours and the second two characters represent the minutes
let hoursRange = savedTime.startIndex...savedTime.startIndex.advancedBy(1) //refers to the first two digits of 4-digit time)
let hours = savedTime[hoursRange]
let minutesRange = savedTime.startIndex.advancedBy(2)...savedTime.endIndex.predecessor() //refers to the last two digits of 4-digit time)
let minutes = savedTime[minutesRange]
print(hours)
print(minutes)
}
}
希望这有用!
麦克
答案 1 :(得分:0)
如果您使用的是UIDatePickerView :(在故事板中设置为Time) 以下函数将保存/加载时间作为NSDate,并且由于您的UIDatePickerView设置为Time,因此只显示小时/分钟
定义一个变量" time"您保存所选日期的地方
var date :NSDate?
使用此功能将数据保存到变量
func save(){
date = datePicker1.date
}
使用此功能从变量
加载数据func load(){
if date != nil {
datePicker1.setDate(date!, animated: true)
}
}