ios iPhone 中的时间选择器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19603212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 02:35:45  来源:igfitidea点击:

Time picker in iPhone

iosiphoneobjective-cuipickerview

提问by Verma

I have 2 field to show the date and time,in one field date is showing correctly by using NSDateFormatter and in another field want to show a time in UIPicker programmatically and put it into the label. Help me in this

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

回答by iPatel

Use UIDatePickerwith Timemode

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

And set selected time in UILabelsuch like

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

Edited:

编辑:

Add following code to datePicker

将以下代码添加到 datePicker

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

And call this method

并调用此方法

- (void)dateChanged:(id)sender
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"hh:mm a"];
    NSString *currentTime = [dateFormatter stringFromDate:self.datePicker.date]; 
    NSLog(@"%@", currentTime);
}