在日期选择器的文本字段中显示时间

时间:2013-08-05 15:03:15

标签: iphone objective-c

我正在尝试在文本字段中的datePicker中显示时间。我已经走到了这一步

UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(112, 88, 97, 30)];
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
[self.view addSubview:textField];

UIDatePicker *datePicker = [[UIDatePicker alloc] init];
datePicker.datePickerMode = UIDatePickerModeDate;
[datePicker addTarget:self action:@selector(datePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
datePicker.timeZone = [NSTimeZone defaultTimeZone];
datePicker.minuteInterval = 5;
datePicker.datePickerMode = UIDatePickerModeTime;

[textField setInputView:datePicker];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle: NSDateFormatterShortStyle];
textField.text = [dateFormatter stringFromDate:datePicker.date];

但是文本字段不会改变

1 个答案:

答案 0 :(得分:3)

您的-(void)datePickerValueChanged:方法是什么样的?

看起来如下:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle: NSDateFormatterShortStyle];
textField.text = [dateFormatter stringFromDate:datePicker.date];

其中textField是正在编辑的textField,而datePicker是其值已更改的日期选择器?