0

我有日期选择器来选择日期并将其显示在标签上。我正在尝试一种yyyy-MM-dd. 但是当我选择任何日期时,标签不会显示我从日期选择器中选择的日期。

我怎样才能显示这种格式yyyy-MM-dd

这是我的代码:

datepicker=[[UIDatePicker alloc]init];
datepicker.datePickerMode=UIDatePickerModeDate;
datepicker.backgroundColor = [UIColor grayColor];
[datepicker setValue:[UIColor whiteColor] forKey:@"textColor"];

UIToolbar *toolBar=[[UIToolbar alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height - 216 - 44, self.view.frame.size.width, 44)];
[toolBar setTintColor:[UIColor blackColor]];
UIBarButtonItem *doneBtn=[[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStylePlain target:self action:@selector(ShowSelectedDate)];
UIBarButtonItem *space=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
[toolBar setItems:[NSArray arrayWithObjects:doneBtn,space,nil]];

[_DOB setInputView: datepicker];

_DOB.inputAccessoryView =toolBar;


-(void)ShowSelectedDate {
    NSDateFormatter *fromatter=[[NSDateFormatter alloc]init];
    [fromatter setDateFormat:@"yyyy-MM-dd"];
    self.DOB.text=[NSString stringWithFormat:@"%@",[fromatter stringFromDate:datepicker.date]];
    [_DOB resignFirstResponder];
}

我的日期选择器如下所示:

在此处输入图像描述

4

1 回答 1

1

您可以实现一个用于拦截UIControlEventValueChanged日期选择器的操作方法。通常这被放置在管理日期选择器的视图控制器类中:

-(IBAction)dateChanged:(UIDatePicker * )inPicker {
     // applying inPicker.date to your label
}

将 action 方法添加到您的选择器,如下所示:

datepicker=[[UIDatePicker alloc]init];
datepicker.datePickerMode=UIDatePickerModeDate;
[datepicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];

视图控制器在哪里self,它实现了dateChanged:. 您也可以使用您的ShowSelectedDate方法:

[datepicker addTarget:self action:@selector(ShowSelectedDate) forControlEvents:UIControlEventValueChanged];

注意:由于ShowSelectedDate不带参数,因此 . 的末尾没有冒号@selector

您还可以将日期选择器作为参数传递给ShowSelectedDate

-(void)ShowSelectedDate:(UIDatePicker * )datepicker {
    NSDateFormatter *fromatter=[[NSDateFormatter alloc]init];
    [fromatter setDateFormat:@"yyyy-MM-dd"];
    self.DOB.text=[NSString stringWithFormat:@"%@",[fromatter stringFromDate:datepicker.date]];
    [_DOB resignFirstResponder];
}

然后你应该应用这个动作:

[datepicker addTarget:self action:@selector(ShowSelectedDate:) forControlEvents:UIControlEventValueChanged];

注意附加的冒号,因为该方法现在有一个参数。

于 2017-11-17T06:46:29.780 回答