iPhone中的时间选择器

时间:2013-10-26 05:29:54

标签: ios iphone objective-c uipickerview

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

1 个答案:

答案 0 :(得分:29)

UIDatePicker模式下使用Time

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);
}