(Swift) Setting UIDatePicker View from User Input

微笑、不失礼 提交于 2020-01-07 03:01:30

问题


First I display a UIDatePicker on the screen and allow the user to choose a date and time. I save that value like this, which gets a date format that looks like this: 6/1/16, 1:47 PM

let time = NSDateFormatter.localizedStringFromDate(datePicker.date, dateStyle: .ShortStyle, timeStyle: .ShortStyle)

Later on in the application, I want users to be able to edit their original date, so when a button is pressed, I would like the UIDatePicker to display the time that they had originally chosen.
I am using the following code to try to make that happen, although the app keeps getting a runtime error because the date is always nil.

let dateFromatter = NSDateFormatter()
let date = dateFromatter.dateFromString("6/1/16, 1:47 PM")
datePicker.setDate(date!, animated: true) 

Thank you for your help!


回答1:


You are having an issue with the date format and not with the date picker.

 @IBOutlet weak var datePicker: UIDatePicker!
 override func viewDidLoad() {
    super.viewDidLoad()

    let dateFromatter = NSDateFormatter()
    dateFromatter.dateFormat = "M/d/yy, H:mm"
    if let date = dateFromatter.dateFromString("6/1/16, 1:47") {
      datePicker.setDate(date, animated: true)
    }
  }



回答2:


For a short style string use below format:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "M/d/yy, H:mm"
dateFormatter.stringFromDate(NSDate())


来源:https://stackoverflow.com/questions/37573897/swift-setting-uidatepicker-view-from-user-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!