CoreData / Swift 2无法保存NSDate类型

时间:2015-10-24 02:21:20

标签: core-data swift2

我在xcode 7中保存日期类型时遇到问题。错误说您无法分配字符串?到NSDate?那么还有另一种方法来保存NSDate类型而不是我正在做的事情吗?同样对于日期字段,我实用地制作了一个日期选择器,以便在其中输入文本,我不知道这是否有所不同。

 @IBOutlet weak var dateField: UITextField!
@IBAction func dateField(sender: UITextField) {

    // This creates an Input View
    let inputView = UIView(frame: CGRectMake(0, 0, self.view.frame.width, 240))

    // This creates an Picker View for the date
    let datePickerView : UIDatePicker = UIDatePicker(frame: CGRectMake(0, 40, 0, 0))
    datePickerView.datePickerMode = UIDatePickerMode.Date
    inputView.addSubview(datePickerView)

    // Makes a toolbar with  a done button at the top of of the date picker view for it to dismiss the moment its clicked
    let doneButton = UIButton(frame: CGRectMake((self.view.frame.size.width/2) - (100/2), 0, 100, 50))
    doneButton.setTitle("Done", forState: UIControlState.Normal)
    doneButton.setTitle("Done", forState: UIControlState.Highlighted)
    doneButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
    doneButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Highlighted)

    // Adds the done button to the datepicker
    inputView.addSubview(doneButton)
    doneButton.addTarget(self, action: "doneButton:", forControlEvents: UIControlEvents.TouchUpInside)

    // Uses the date picker as a date picker using the format made in the function 'datePickerChanged'
    sender.inputView = inputView
    datePickerView.addTarget(self, action: Selector("datePickerChanged:"), forControlEvents: UIControlEvents.ValueChanged)

    // Immediately sets a date on start
    datePickerChanged(datePickerView)

}


func doneButton(sender : UIButton) {
    dateField.resignFirstResponder()
}

func datePickerChanged(sender : UIDatePicker) {
    // Creates a date sytle format for the date picker
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
    dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle
    dateField.text = dateFormatter.stringFromDate(sender.date)
}

1 个答案:

答案 0 :(得分:1)

试试这个 - 我不会问为什么你使用DatePicker在textField中添加日期,然后再将文本从textField转换为日期

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = /*Use the same format as is output by your datepicker*/
let date = dateFormatter.dateFromString(/*your_date_string*/)