标签:
效果如下:
ViewController.h
1 #import <UIKit/UIKit.h> 2 3 @interface ViewController : UIViewController 4 @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 ViewController 10 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 addTarget:self 27 action:@selector(pickerDidChange:) forControlEvents:UIControlEventValueChanged]; 28 [self.view addSubview:_datePChoice]; 29 30 UIButton *btnChoice = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 150, 40)]; 31 newPoint.y += 160; 32 btnChoice.center = newPoint; 33 btnChoice.layer.masksToBounds = YES; 34 btnChoice.layer.cornerRadius = 10.0; 35 btnChoice.layer.borderColor = [UIColor colorWithRed:0.655 green:0.619 blue:0.601 alpha:1.000].CGColor; 36 btnChoice.layer.borderWidth = 2.0; 37 [btnChoice setTitle:@"显示日期" forState:UIControlStateNormal]; 38 [btnChoice setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; 39 [btnChoice addTarget:self 40 action:@selector(buttonDidPush:) 41 forControlEvents:UIControlEventTouchUpInside]; 42 [self.view addSubview:btnChoice]; 43 } 44 45 - (void)pickerDidChange:(UIDatePicker *)sender { 46 NSLog(@"%@", [sender.date description]); //2015-04-19 5:42:58 +0000;显示时区少了8个钟,所以用NSDateFormatter显示的时间才算正常时区时间 47 } 48 49 - (void)buttonDidPush:(UIButton *)sender { 50 NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 51 [formatter setDateFormat:@"yyyy/MM/dd HH:mm"]; //2015/04/19 13:42 52 NSString *strCurrentDate = [formatter stringFromDate:_datePChoice.date]; 53 54 UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"选择的日期" 55 message:strCurrentDate 56 delegate:nil 57 cancelButtonTitle:nil 58 otherButtonTitles:@"确定", nil]; 59 [alertV show]; 60 } 61 62 @end
标签:
原文地址:http://www.cnblogs.com/huangjianwu/p/4579210.html