效果如下:
ViewController.h
1 #import2 3 @interface ViewController : UIViewController4 @property (strong, nonatomic) UIDatePicker *datePChoice;5 6 @end
ViewController.m
1 #import "ViewController.h" 2 3 @interface ViewController () 4 - (void)layoutUI; 5 - (void)pickerDidChange:(UIDatePicker *)sender; 6 - (void)buttonDidPush:(UIButton *)sender; 7 @end 8 9 @implementation ViewController10 11 - (void)viewDidLoad {12 [super viewDidLoad];13 14 [self layoutUI];15 }16 17 - (void)didReceiveMemoryWarning {18 [super didReceiveMemoryWarning];19 // Dispose of any resources that can be recreated.20 }21 22 - (void)layoutUI {23 _datePChoice = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];24 CGPoint newPoint = self.view.center;25 _datePChoice.center = newPoint;26 _datePChoice.datePickerMode = UIDatePickerModeDateAndTime; //默认值是UIDatePickerModeDateAndTime27 [_datePChoice addTarget:self28 action:@selector(pickerDidChange:) forControlEvents:UIControlEventValueChanged];29 [self.view addSubview:_datePChoice];30 31 UIButton *btnChoice = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 280, 40)];32 newPoint.y += 160;33 btnChoice.center = newPoint;34 btnChoice.layer.masksToBounds = YES;35 btnChoice.layer.cornerRadius = 10.0;36 btnChoice.layer.borderColor = [UIColor colorWithRed:0.655 green:0.619 blue:0.601 alpha:1.000].CGColor;37 btnChoice.layer.borderWidth = 2.0;38 [btnChoice setTitle:@"切换日期选择器框的显示样式" forState:UIControlStateNormal];39 [btnChoice setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];40 [btnChoice addTarget:self41 action:@selector(buttonDidPush:)42 forControlEvents:UIControlEventTouchUpInside];43 [self.view addSubview:btnChoice];44 }45 46 - (void)pickerDidChange:(UIDatePicker *)sender {47 NSLog(@"%@", [_datePChoice.date description]); //2015-04-19 11:00:03 +0000;显示时区少了8个钟,所以用NSDateFormatter显示的时间才算正常时区时间48 }49 50 - (void)buttonDidPush:(UIButton *)sender {51 //设置日期选择器框的显示样式52 static NSInteger i = 1;53 switch (i%4) {54 case 0:55 _datePChoice.datePickerMode = UIDatePickerModeDateAndTime; //UI效果:4月19日 周日 下午 7 0056 break;57 case 1:58 _datePChoice.datePickerMode = UIDatePickerModeDate; //UI效果:2005年 4月 19日59 break;60 case 2:61 _datePChoice.datePickerMode = UIDatePickerModeTime; //UI效果:下午 7 0062 break;63 case 3:64 _datePChoice.datePickerMode = UIDatePickerModeCountDownTimer; //UI效果:0hours 1min65 break;66 }67 i++;68 }69 70 @end