swift2 CoreData/Swift 2在保存NSDate类型时出现问题

yshpjwxd  于 2022-11-06  发布在  Swift
关注(0)|答案(1)|浏览(217)

我在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)
}
rnmwe5a2

rnmwe5a21#

试试这个- * 我不会问为什么要使用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*/)

相关问题