仅在单击UITextfield时显示UIDatePicker

时间:2014-07-30 09:11:12

标签: objective-c xcode uitextfield uidatepicker

我想,当我点击我的UITextfield时,弹出一个UIDatePicker,但我只希望它显示时间,而不是日期。到目前为止我做了什么

-(void)updateTextField:(id)sender
{
    UIDatePicker *picker = (UIDatePicker*)self.myTextField.inputView;
    self.myTextField.text = [NSString stringWithFormat:@"%@",picker.date];
}
- (void)viewDidLoad
{
    UIDatePicker *datePicker = [[UIDatePicker alloc]init];
    [datePicker setDate:[NSDate date]];
    [datePicker addTarget:self action:@selector(updateTextField:) forControlEvents:UIControlEventValueChanged];
    [self.myTextField setInputView:datePicker];
}

当我在模拟器中尝试这个时,会出现这种情况,这是我不想要的: http://prntscr.com/47rddt

2 个答案:

答案 0 :(得分:2)

要仅显示在文本字段中打印日期的时间,请使用日期格式化程序,而不是打印整个日期对象。

NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateFormat:@"HH:mm"];
self.myTextField.text = [timeFormatter stringFromDate:picker.date];

答案 1 :(得分:1)

有四种日期选择器模式可供选择。您可以根据需要设置模式。

1) UIDatePickerModeTime
2) UIDatePickerModeDate
3) UIDatePickerModeDateAndTime
4) UIDatePickerModeCountDownTimer

datePickerMode设置为UIDatePickerModeTime

- (void)viewDidLoad
{
    UIDatePicker *datePicker = [[UIDatePicker alloc]init];
    [datePicker setDate:[NSDate date]];
    datePicker.datePickerMode = UIDatePickerModeTime;
    [datePicker addTarget:self action:@selector(updateTextField:) forControlEvents:UIControlEventValueChanged];
    [self.myTextField setInputView:datePicker];
}

<强>更新

在文本字段中设置时间时使用以下代码。

-(void)updateTextField:(UIDatePicker *)dtPicker{
    NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
    [timeFormatter setDateFormat:@"HH:mm"];
    self.myTextField.text = [timeFormatter stringFromDate:dtPicker.date];
}