SWIFT:从文本字段格式化为日期不起作用

问题描述 投票:-1回答:1

我有以下功能,我需要标签根据所选日期更新周数。日期选择由UIDatePicker完成。

如果我写print(pickedDate)我得到刚刚由UIDatePicker选择的日期,所以这似乎工作正常。 但是,如果我打印(selectedDate)我得到nil,因此公式中的错误致命错误:在展开Optional值时意外发现nil

这是我的代码:

func selectWeek () {

        let formatter = DateFormatter()

        let pickedDate = dateEntry.text
        let selectedDate = formatter.date(from: pickedDate!)


        if (weekTwoIntervalJan! ... weekThreeIntervalJan!).contains(selectedDate!) {
            weekNrLabel.text = "Week 3"
        }
        else if (weekThreeIntervalJan! ... weekFourIntervalJan!).contains(selectedDate!) {
            weekNrLabel.text = "Week 4"
        }


        else if (startDateFebDate! ... weekOneIntervalFeb!).contains(selectedDate!) {
            weekNrLabel.text = "Week 1"
        }

        else if (weekOneIntervalFeb! ... weekTwoIntervalFeb!).contains(selectedDate!) {
            weekNrLabel.text = "Week 2"
        }
        else if (weekTwoIntervalFeb! ... weekThreeIntervalFeb!).contains(selectedDate!) {
            weekNrLabel.text = "Week 3"
        }
        else if (weekThreeIntervalFeb! ... weekFourIntervalFeb!).contains(selectedDate!) {
            weekNrLabel.text = "Week 4"
        }


        else {
            print("fail")



}
swift date nsdateformatter dateformatter
1个回答
-1
投票

你的UIDatePicker的名字是什么?

也许你想做(用datePicker的名字取代UIDatePicker):

let selectedDate = datePicker.date
© www.soinside.com 2019 - 2024. All rights reserved.