如何在从UITextField获取的CoreData中保存NSDate

时间:2015-10-24 08:31:26

标签: swift core-data nsdate

我在确定如何保存从UITextField到CoreData的日期方面遇到了一些麻烦,也使其可编辑,因此当用户回到他们可以更改它的日期时。这是我到目前为止的代码:

@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)
}
 var dateSave : Product? = nil
 let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext

if (dateSave != nil) {
        let dateFormatter = NSDateFormatter()
        var dateIn = dateFormatter.dateFromString(dateField.text!)
        dateIn = dateSave?.date
    }
func createProduct() {
    // Creates an Entity Description for the Core Data
    let entityDescription = NSEntityDescription.entityForName("dateSaved", inManagedObjectContext: moc)
    let datesaved = dateSaved(entity: entityDescription!, insertIntoManagedObjectContext: moc)
    // Creates Dates to save in coredata
    let dateFormatter = NSDateFormatter()
    var dateIn = dateFormatter.dateFromString(dateField.text!)
    product.date = dateIn
    do {
        try moc.save()
    } catch {
        return
    }
}
func editProduct() {
    // this function is for the edited dates that were already created
    let dateFormatter = NSDateFormatter()
    var dateIn = dateFormatter.dateFromString(dateField.text!)
    product?.date = dateIn
    do {
        try moc.save()
    } catch {
        return
    }
}
func dismissTVC() {
    navigationController?.popToRootViewControllerAnimated(true)
}

@IBAction func saveTapped(sender: AnyObject) {
    if (product != nil) {
        editProduct()
    } else {
        createProduct()
    }
    dismissTVC()
}

@IBAction func cancelTapped(sender: AnyObject) {
    dismissTVC()
}

2 个答案:

答案 0 :(得分:1)

使用SMDatePicker。它是用Swift编写的,易于使用。带UIToolbar的可自定义UIDatePicker。易于设置,使用和安装定制

实现UITextFieldDelegate的Delegate方法:

// MARK: - TextField Delegate Methods
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
    if textField == self.myDateTextField {
        textField.resignFirstResponder()

        //show SMDatePicker
        var picker: SMDatePicker = SMDatePicker()
        picker.pickerMode = UIDatePickerMode.Date
        picker.showPickerInView(view, animated: true)
        picker.delegate = self

        return false
    }
    return true
}

// MARK: SMDatePickerDelegate
func datePicker(picker: SMDatePicker, didPickDate date: NSDate) {
     let dateFormater:NSDateFormatter = NSDateFormatter()
     dateFormater.dateFormat = "dd/MM/yyyy"
     let formatedDate:NSString = dateFormater.stringFromDate(date)
     self.myDateTextField.text = formatedDate as String
}

func datePickerDidCancel(picker: SMDatePicker) {
     print("Date Picker Cancel")
}

希望它对你有用。

<强>更新

我在Swift中为你编写了这个方法,以便在CoreData中保存日期。希望它对你有用。

func createProduct() {

    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext

    // Creates an Entity Description for the Core Data
    let productEntity = NSEntityDescription.insertNewObjectForEntityForName("Product", inManagedObjectContext: managedContext) as! Product

    // Creates Dates to save in coredata
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "dd/MM/yyyy"
    dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC")

    let expiryDate = dateFormatter.dateFromString(dateField.text!)
    productEntity.expiryDate = expiryDate

    do {
        try managedContext.save()
    } catch {
        print("Unable to save Product in CoreData")
    }
}

答案 1 :(得分:0)

您可能最好创建一个自定义UITextField类,该类具有您使用DatePicker设置的NSDate属性 - 并显示当前设置的日期。这样您就不必担心从UITextField.Text转换回日期,只需使用CustomUITextField.date属性。

我使用的自定义UIButton看起来就像一个TextField,除非它是可编辑的并且用户点击它我弹出一个DatePicker,以便用户可以编辑日期。当他们关闭DatePicker时,它会将日期传递回自定义按钮控件并设置其日期属性,然后使用适当格式化的日期或时间更新按钮标签。如果你愿意,我可以发布Obj-C课程 - 对不起 - 没有Swift课程...但你应该能够或多或少地使用它们。