计算年龄:DateComponents上对成员的模糊引用

时间:2019-04-21 11:33:35

标签: ios swift xcode

我正在尝试提出一个代码,该代码根据分配给文本字段的datePicker计算年龄。我得到正确的日期就好,它通过了打印测试。但是,在尝试使dateComponents正常工作时,出现“对成员'dateComponents(_:from:to :)'的含糊引用”“错误。 -这与一个stackoverflow通知我的代码不同,我正在尝试使用datepicker到达那里。 -

我到处寻找在线解决方案,但似乎无法超越。你能帮忙吗?

-初学者总数

@objc func dateChanged(datePicker: UIDatePicker) {

    let myCalendar = Calendar(identifier: .gregorian)
    let dmy = myCalendar.dateComponents([.day, .month, .year], from: Date())

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd/MM/yyyy"

    inputTextField.text = dateFormatter.string(from: datePicker.date)

    let birthdayDate = dateFormatter.string(from: datePicker.date)
    print(birthdayDate)

    let now = NSDate()
    let ageComponents = myCalendar.dateComponents(.year, from: birthdayDate, to: now) //Ambiguous reference to member 'dateComponents(_:from:to:)'
    let age = ageComponents.year!

    label.text = age

    view.endEditing(true)

}

2 个答案:

答案 0 :(得分:1)

您的代码中有几个问题

  1. 您应该在Swift中使用Date,而不是NSDate
  2. birthdayDateString,但是from:参数必须是Date的实例
  3. components参数需要设置。

更正这些内容将为您提供:

@objc func dateChanged(datePicker: UIDatePicker) {

    let birthdayDate = datePicker.date
    let myCalendar = Calendar(identifier: .gregorian)
    let dmy = myCalendar.dateComponents([.day, .month, .year], from: Date())

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd/MM/yyyy"

    inputTextField.text = dateFormatter.string(from: birthdayDate)

    let now = Date()
    let ageComponents = myCalendar.dateComponents([.year], from: birthdayDate, to: now)
    let age = ageComponents.year!

    label.text = "\(age)"

    view.endEditing(true)

}

答案 1 :(得分:0)

这里:

qdapRegex

您直接将let ageComponents = myCalendar.dateComponents(.year, from: birthdayDate, to: now) 传递给.year,但实际上它期望一个dateComponents。另外,Set<DateComponents>birthdayDate,而不是String。您应该改为传递Date。因此,您应该这样做:

datePicker.date

此外,let ageComponents = myCalendar.dateComponents([.year], from: datePicker.date, to: now) 应该是now,而不是Date