这里实现的是当没有进行选择的时候 dataLabel显示当前的时间 当进行选择后它显示选择的时间
具体代码如下:
@interface ViewController ()
@property (nonatomic, strong) UIDatePicker *dataPicker;
@property (nonatomic, strong) UILabel *dataLabel;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self initLayout];
[self.dataPicker addTarget:self action:@selector(dataPickerAction:) forControlEvents:UIControlEventValueChanged];
//下面这段代码 是显示当前日期时间
NSDateFormatter *dateformatter = [NSDateFormatter new];
dateformatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSString *dateString = [dateformatter stringFromDate:[NSDate date]];
self.dataLabel.text = dateString;
}
- (void)initLayout {
self.dataPicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(20, 20, 400, 200)];
[self.view addSubview:self.dataPicker];
self.dataLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 300, 400, 50)];
self.dataLabel.textAlignment = 1;
self.dataLabel.center = self.view.center;
self.dataLabel.backgroundColor = [UIColor orangeColor];
[self.view addSubview:self.dataLabel];
}
- (void)dataPickerAction:(UIDatePicker *)sender {
NSDateFormatter *dateformatter = [NSDateFormatter new];
dateformatter.dateFormat = @"yyyy-MM-dd HH-mm-ss";
NSString *dateString = [dateformatter stringFromDate:self.dataPicker.date];
self.dataLabel.text = dateString;
}