在Swift(1.2)中从String设置UIDateFormatter

时间:2017-06-07 18:06:19

标签: ios swift date set uidatepicker

我想要做的是从保存它的字符串中检索日期,并将其传递给UIDatePicker(滚动日期选择器元素),所以这是我的代码片段:

@IBOutlet weak var myDatePicker: UIDatePicker!
@IBOutlet weak var nameTextField: UITextField!   

@IBOutlet weak var saveButton: UIBarButtonItem!

    //converting date to string to show in table cell

    func dateToString (date: NSDate) -> String {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
        return dateFormatter.stringFromDate(date)
    }

    //converting string from table cell to edit date

    func stringToDate (string: NSString) -> NSDate {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
        return dateFormatter.dateFromString(dateToString (myDatePicker.date))!
    }

// here we are saving our data picked from text field and date picker UIs

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if saveButton === sender {
            let name = nameTextField.text ?? ""
            let date = dateToString (myDatePicker.date) ?? ""
            item = Item (name: name, date: date)
        }
    }

// Here we are retrieving data when press tableCell cell:

override func viewDidLoad() {
        super.viewDidLoad()
        if let item = item {
            nameTextField.text = item.name
            myDatePicker.setDate(stringToDate(item.date), animated: true)

            // also need to pass date smhw
        }
    }

从UIDatePicker保存到UITableCell中的字符串 - 没问题,将字符串(UILabel)传递给UITextField - 没问题,但是我无法将字符串传递给UIDatePicker。 它没有任何警告,构建 - 没有问题,启动,但没有发生任何动作。 请就此问题提出解决方案。我正在编写swift 1.2。

1 个答案:

答案 0 :(得分:0)

func stringToDate (string: String) -> NSDate {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
        return dateFormatter.dateFromString(string)!
    }

这很有效。