简体   繁体   中英

How do I add a date of birth UIDatePicker to UITextField?

I request the users date of birth on the sign up screen of my application. I can't figure out how to get a date of birth UIDatePicker to display. I tried using the following code but it only displays the date and time:

 UIDatePicker *dp = [[UIDatePicker alloc]init];
_textBirthday.inputView = dp;

Also, how would I set it so it only accepts users born after a certain year?

1) in the .h file of your view controller make sure you assign textfield delegate:

@interface YourViewController : UIViewController <UITextFieldDelegate>

and also have an IBOutlet of the birthday Textfield

2) declare a date picker as a class variable to make it accessible from all different methods in class. in the .m file do the following after import and before implementation:

@interface YourViewController () {
UIDatePicker *datePicker;
}
@end

3) in viewdidload:

// make the textfield its own delegate
self.BirthdateTextfield.delegate = self;

// alloc/init your date picker, and (optional) set its initial date
datePicker = [[UIDatePicker alloc]init];
[datePicker setDate:[NSDate date]]; //this returns today's date

// theMinimumDate (which signifies the oldest a person can be) and theMaximumDate (defines the youngest a person can be) are the dates you need to define according to your requirements, declare them:

// the date string for the minimum age required (change according to your needs) 
NSString *maxDateString = @"01-Jan-1996";
// the date formatter used to convert string to date
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// the specific format to use
dateFormatter.dateFormat = @"dd-MMM-yyyy";
// converting string to date
NSDate *theMaximumDate = [dateFormatter dateFromString: maxDateString];

// repeat the same logic for theMinimumDate if needed

// here you can assign the max and min dates to your datePicker 
[datePicker setMaximumDate:theMaximumDate]; //the min age restriction 
[datePicker setMinimumDate:theMinimumDate]; //the max age restriction (if needed, or else dont use this line)

// set the mode
[datePicker setDatePickerMode:UIDatePickerModeDate];

// update the textfield with the date everytime it changes with selector defined below
[datePicker addTarget:self action:@selector(updateTextField:) forControlEvents:UIControlEventValueChanged];

// and finally set the datePicker as the input mode of your textfield
[self.BirthdateTextfield setInputView:datePicker];

4) in same .m file, define the selector that will update textfield each time the date picker changes:

-(void)updateTextField:(id)sender {
    UIDatePicker *picker = (UIDatePicker*)self.BirthdateTextfield.inputView;
    self.BirthdateTextfield.text = [self formatDate:picker.date];
}

5) last but not least, this is the method called before assigning the date to the textfield.text (textfield.text needs a string not a date):

- (NSString *)formatDate:(NSDate *)date {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterShortStyle];
    [dateFormatter setDateFormat:@"dd-MMM-yyyy"];
    NSString *formattedDate = [dateFormatter stringFromDate:date];
    return formattedDate;
}

enjoy coding!

Use the following code you will get an output automatically:

- (void)viewDidLoad {
[super viewDidLoad];

UIDatePicker *datePicker = [[UIDatePicker alloc]init];
[datePicker setDate:[NSDate date]];
datePicker.datePickerMode = UIDatePickerModeDate;
[datePicker addTarget:self action:@selector(dateTextField:) forControlEvents:UIControlEventValueChanged];
[self.dobTextField setInputView:datePicker];
}

-(void) dateTextField:(id)sender{
 UIDatePicker *picker = (UIDatePicker*)self.dobTextField.inputView;
[picker setMaximumDate:[NSDate date]];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSDate *eventDate = picker.date;
[dateFormat setDateFormat:@"dd/MM/yyyy"];
NSString *dateString = [dateFormat stringFromDate:eventDate];
self.dobTextField.text = [NSString stringWithFormat:@"%@",dateString];
}

Here is the Swift 4 code:

override func viewDidLoad() {
    super.viewDidLoad()
  showDatePicker()
}

//MARK: Show Date Picker
func showDatePicker(){
    //Formate Date
    datePicker.datePickerMode = .date
    //ToolBar
    let toolbar = UIToolbar();
    toolbar.sizeToFit()
    //done button & cancel button
    let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(donedatePicker))
    let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
    let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelDatePicker))

    toolbar.setItems([cancelButton,spaceButton,doneButton], animated: false)

    // add toolbar to textField
    dateOfBirthTxtFldRef.inputAccessoryView = toolbar
    // add datepicker to textField
    dateOfBirthTxtFldRef.inputView = datePicker
}

@objc func donedatePicker(){
    //For date formate
    let formatter = DateFormatter()
    formatter.dateFormat = "dd MMMM yyyy"
    dateOfBirthTxtFldRef.text! = formatter.string(from: datePicker.date)
    //dismiss date picker dialog
    self.view.endEditing(true)
}

@objc func cancelDatePicker(){
    //cancel button dismiss datepicker dialog
    self.view.endEditing(true)
}

Set the datePickerMode to UIDatePickerModeDate .

datePicker.datePickerMode = UIDatePickerModeDate;

Apple Docs : The date picker displays months, days of the month, and years. The exact order of these items depends on the locale setting. An example of this mode is [ November | 15 | 2007 ]. Available in iOS 2.0 and later.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM