I have a textField in my view and under it a picker.

I need when the user chooses a date from the datePicker the textField to show the exact value of the date.

How do i get the date from the dateField?

有帮助吗?

解决方案

Set the value_changed event of your DatePicker to a IBAction :

example :

- (IBAction) dateChanged:(id)sender {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    self.currentTextField.text = [dateFormatter stringFromDate:[self.datePicker date]];
}

其他提示

You can have a method to update the date changed from the UIDatePicker by setting an action to Value Changed event in the connection inspector, implement the action to set the value to textField something like this

- (IBAction)datePickerValueChanged:(id) sender{

    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    df.dateStyle = NSDateFormatterMediumStyle;

    self.textfield.text = [NSString stringWithFormat:@"%@",[df stringFromDate:datePicker.date]];

}

OR you could add selector to the UIDatePicker

[datePicker addTarget:self action:@selector(updateMyDate:) forControlEvents:UIControlEventEditingChanged];

UIDatePicker has a date property. You can access the NSDate via this property.

Then you probably need to use NSDateFormatter to create a NSString from your NSDate, and be able to display it in your UITextField.

In its most straightforward way, your code should look like this:

myTextField.text = [myDateFormatter stringFromDate:myDatePicker.date];
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    df.dateFormat = "dd-MMMM-yyyy hh:mm a"

    //To show date in textfield     

    myTextField.text = [df stringFromDate:datePicker.date];

    //To show selected date on datepicker from textfield 

   datePicker.date = df.dateFromString(myTextField.text)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top