UIDataPicker 时间选择器

时间:2022-09-16 06:25:04

自用时间选择器

 @interface ViewController ()
{
UILabel *cityLabel;
UIDatePicker *datePicker;
}
//@property(nonatomic,strong)ZHPickView *pickview;
@end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
cityLabel=[[UILabel alloc]init];
cityLabel.frame=CGRectMake(, , , );
cityLabel.text=@"abcdefg";
[self.view addSubview:cityLabel]; UIButton *btn=[[UIButton alloc]init];
btn.frame=CGRectMake(, , , );
btn.backgroundColor=[UIColor yellowColor];
[btn addTarget:self action:@selector(add) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn]; //datePicker宽度320像素和高度216像素,系统都设置好了,只需设置一下他的远点坐标,
datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(, ,[UIScreen mainScreen].bounds.size.width, )];
NSLocale *locale = [[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"];
datePicker.locale = locale;
//设置datePicker显示模式
[datePicker setDatePickerMode:UIDatePickerModeDate];
//DatePicker属于UIControl子类,可以触发事件,当滚动滑轮滑轮停下后就调用这个方法了
[datePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
datePicker.hidden=YES;
[self.view addSubview:datePicker];
} -(void)add{
datePicker.hidden=NO;
} -(void)dateChanged:(id)sender
{
UIDatePicker *control = (UIDatePicker*)sender;
//把当前控件设置的时间赋给date
NSDate *date = control.date;
// 将NSDate格式装换成NSString类型
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
//设置日历显示格式
[dateFormatter setDateFormat:@"yyyy/MM/dd"];
//把日历时间传给字符串
NSString *strDate = [dateFormatter stringFromDate:date];
NSString *message = [[NSString alloc]initWithFormat:@"%@",strDate];
cityLabel.text=message; }