简体   繁体   English

我如何使datePicker在textField上显示日期?

[英]How can i make a datePicker show the date on a textField?

I have a textField in my view and under it a picker. 我的视图中有一个textField,下面有一个选择器。

I need when the user chooses a date from the datePicker the textField to show the exact value of the date. 当用户从datePicker中选择日期时,我需要textField以显示日期的确切值。

How do i get the date from the dateField? 如何从dateField获取日期?

Set the value_changed event of your DatePicker to a IBAction : 将DatePicker的value_changed事件设置为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 您可以通过在连接检查器中将操作设置为Value Changed事件来更新从UIDatePicker更改的日期的方法,实现将该值设置为textField的操作,如下所示

- (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 或者,您可以将选择器添加到UIDatePicker

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

UIDatePicker has a date property. UIDatePicker具有date属性。 You can access the NSDate via this property. 您可以通过此属性访问NSDate

Then you probably need to use NSDateFormatter to create a NSString from your NSDate , and be able to display it in your UITextField . 然后,您可能需要使用NSDateFormatterNSDate创建一个NSString ,并能够在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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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