日期格式在IOS中不起作用

时间:2017-11-17 06:13:16

标签: ios date uidatepicker target-action

我有日期选择器来选择日期并在标签上显示。我正在尝试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];
}

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

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以实施拦截日期选择器的UIControlEventValueChanged的操作方法。通常它放在管理日期选择器的视图控制器类中:

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

将操作方法​​添加到您的选择器中,如下所示:

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];

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