6

我有 2 个字段来显示日期和时间,在一个字段中使用 NSDateFormatter 正确显示日期,在另一个字段中希望以编程方式在 UIPicker 中显示时间并将其放入标签中。在这方面帮助我

4

1 回答 1

30

UIDatePickerTime模式一起使用

self.datePicker = [[UIDatePicker alloc] init];
self.datePicker.frame = CGRectMake(0, 0, self.view.frame.size.width, 180.0f); // set frame as your need
self.datePicker.datePickerMode = UIDatePickerModeTime;
[self.view addSubview: self.datePicker];

并设置选定的UILabel时间

UILabel  * label1 = [[UILabel alloc] initWithFrame:CGRectMake(40, 70, 300, 50)];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh:mm a"];
NSString *currentTime = [dateFormatter stringFromDate:self.datePicker.date];    
label1.text = currentTime;
[self.view addSubview:label1];

编辑:

将以下代码添加到 datePicker

[datePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];

并调用此方法

- (void)dateChanged:(id)sender
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"hh:mm a"];
    NSString *currentTime = [dateFormatter stringFromDate:self.datePicker.date]; 
    NSLog(@"%@", currentTime);
}
于 2013-10-26T05:34:40.927 回答