0

I'm trying to add a date format in my UITextField, I have some tutorials but I think with the new version of swift I have some errors.

I'm trying to display a UIDatePicker on UITextField tap:

@IBAction func tfDateNaissanceEditing(sender: UITextField) {
    let datePickerView:UIDatePicker = UIDatePicker()

    datePickerView.datePickerMode = UIDatePickerMode.Date

    sender.inputView = datePickerView

    datePickerView.addTarget(self, action: Selector("datePickerValueChanged:"), forControlEvents: UIControlEvents.ValueChanged)

}

@IBAction func tfDateNaissanceChanged(sender: UITextField) {
    let dateFormatter = NSDateFormatter()

    dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle

    dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle

    tfDateNaissance.text = dateFormatter.stringFromDate(sender.date)
}

But I get an error on sender.date : UITextField has no member date.

And I want to know, if I can get the date, how I would check if the user is older than 16 years old for example ?

error

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
2015-12-22 16:12:51.699 Solutis[1315:72750] -[Solutis.DemandeGratuiteViewController datePickerValueChanged:]: unrecognized selector sent to instance 0x7aa7e000
2015-12-22 16:12:51.707 Solutis[1315:72750] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Solutis.DemandeGratuiteViewController datePickerValueChanged:]: unrecognized selector sent to instance 0x7aa7e000'
*** First throw call stack:
(
    0   CoreFoundation                      0x002e5a84 __exceptionPreprocess + 180
    1   libobjc.A.dylib                     0x02185e02 objc_exception_throw + 50
    2   CoreFoundation                      0x002eedd3 -[NSObject(NSObject) doesNotRecognizeSelector:] + 275
    3   CoreFoundation                      0x0022ccdd ___forwarding___ + 1037
    4   CoreFoundation                      0x0022c8ae _CF_forwarding_prep_0 + 14
    5   libobjc.A.dylib                     0x0219a0b5 -[NSObject performSelector:withObject:withObject:] + 84
    6   UIKit                               0x00cd016a -[UIApplication sendAction:to:from:forEvent:] + 118
    7   UIKit                               0x00cd00e9 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 64
    8   UIKit                               0x00e6e19f -[UIControl sendAction:to:forEvent:] + 79
    9   UIKit                               0x00e6e51f -[UIControl _sendActionsForEvents:withEvent:] + 408
    10  UIKit                               0x00e6e1df -[UIControl sendActionsForControlEvents:] + 48
    11  UIKit                               0x0166fab1 -[_UIDatePickerView pickerView:didSelectRow:inComponent:] + 607
    12  UIKit                               0x00caecd7 -[UIPickerView _sendSelectionChangedForComponent:notify:] + 124
    13  UIKit                               0x00caee68 -[UIPickerView _sendSelectionChangedFromTable:notify:] + 137
    14  UIKit                               0x014ba31f -[UIPickerTableView _scrollingFinished] + 218
    15  UIKit                               0x014ba3d5 -[UIPickerTableView scrollViewDidEndDecelerating:] + 33
    16  UIKit                               0x00dc55a2 -[UIScrollView(UIScrollViewInternal) _stopScrollDecelerationNotify:] + 1306
    17  UIKit                               0x00dc582c -[UIScrollView(UIScrollViewInternal) _stopScrollingNotify:pin:tramplingDragFlags:] + 523
    18  UIKit                               0x00dc587e -[UIScrollView(UIScrollViewInternal) _stopScrollingNotify:pin:] + 57
    19  UIKit                               0x00dbaf7d -[UIScrollView _smoothScrollWithUpdateTime:] + 230
    20  UIKit                               0x00dbc41b -[UIScrollView _smoothScrollDisplayLink:] + 289
    21  QuartzCore                          0x05be0cfa _ZN2CA7Display15DisplayLinkItem8dispatchEv + 62
    22  QuartzCore                          0x05be0ba3 _ZN2CA7Display11DisplayLink14dispatch_itemsEyyy + 421
    23  QuartzCore                          0x05be10b5 _ZN2CA7Display16TimerDisplayLink8callbackEP16__CFRunLoopTimerPv + 123
    24  CoreFoundation                      0x00237576 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 22
    25  CoreFoundation                      0x00236f72 __CFRunLoopDoTimer + 1250
    26  CoreFoundation                      0x001f525a __CFRunLoopRun + 2202
    27  CoreFoundation                      0x001f4706 CFRunLoopRunSpecific + 470
    28  CoreFoundation                      0x001f451b CFRunLoopRunInMode + 123
    29  GraphicsServices                    0x05656664 GSEventRunModal + 192
    30  GraphicsServices                    0x056564a1 GSEventRun + 104
    31  UIKit                               0x00cce1eb UIApplicationMain + 160
    32  Solutis                             0x000652fc main + 140
    33  libdyld.dylib                       0x02be9a21 start + 1
    34  ???                                 0x00000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

More than 18 years old:

func verifAge(){
    let start = String(tfDateNaissance.text!)

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "MM-dd-yyyy"

    let startDate:NSDate = dateFormatter.dateFromString(start)

    let cal = NSCalendar.currentCalendar()


    let components = cal.components(.Year, fromDate: startDate, toDate: NSDate(), options: [])


    print(components)
}

fatal error: unexpectedly found nil while unwrapping an Optional value

Ben
  • 761
  • 1
  • 12
  • 35
  • In your second action, you try to use a method `.date` for an instance of type `UITextField`, whereas the latter type does not include a method named `.date`. (`tfDateNaissance.text = dateFormatter.stringFromDate(**sender.date**)`). Perhaps you intended to use `sender.text` here instead? – dfrib Dec 22 '15 at 14:42

1 Answers1

0

First, to get the date you want from the DatePicker, the sender is a type of UIDatePicker, not UITextField claimed in your method input.

Second, refer to this answer, you can get the age by

let ageComponents = calendar.components(.Year, fromDate: sender.date, toDate: NSDate(), options: [])

EDIT

You added a selector method named datePickerValueChanged, but the the action is named tfDateNaissanceChanged. Or I should put it in this way that you don't need to listen to TextView value changed, just need to implement the method for DataPicker value changed.

Community
  • 1
  • 1
zc246
  • 1,514
  • 16
  • 28
  • I changed sender to UIDatePicker but I get an error when I chose a date, look my edit please. – Ben Dec 22 '15 at 15:13
  • @Ben you need declare let datePickerView = UIDatePicker() in your view controller class (move it out of the IBAction method) and just use datePickerView.date – Leo Dabus Dec 22 '15 at 15:14
  • @LeoDabus Hi, this Picker view have a bad format, they're the time – Ben Dec 22 '15 at 15:19
  • @Ben, make sure your have the right function named `datePickerValueChanged` – zc246 Dec 22 '15 at 15:21
  • @Ben There is no time without a date – Leo Dabus Dec 22 '15 at 15:22
  • @LeoDabus I did: tfDateNaissance.inputView = datePickerView – Ben Dec 22 '15 at 15:23
  • @zcui93 Sorry for my bad, I have a question here my date is displayed on English version, but if I install my app on a French device, it will automatically change ? And nos to check age I go on your refer answer, I'll come back to you if I have a problem – Ben Dec 22 '15 at 15:31
  • @Ben, yes. The `NSDateFormatterStyle`s you are using now, will use the user's locale formats – zc246 Dec 22 '15 at 15:37
  • I tryed to st my location on Debug > Location > City Run, but I look doesn't work, and I have an another problem, when I run my form, and on first time tap on the text field I have the keyboard – Ben Dec 22 '15 at 15:42
  • Debug > Location is to simulate the GPS location, but the locale is only related to the iOS system region setting. You should probably raise another question regarding your viewing issue, as different code/storyboard issue might be related. – zc246 Dec 22 '15 at 15:45
  • Look edit please I have an error on let startDate, I wanna show the différence – Ben Dec 23 '15 at 13:49
  • Which line does the error occur? Did you have the `startDate` correctly parsed? – zc246 Dec 23 '15 at 13:52
  • sorry for late components print that: Calendar Year: 22 how to get only the value ? – Ben Jan 04 '16 at 14:58
  • Please just try. There should be something close to `components.year` – zc246 Jan 04 '16 at 15:09