您的位置:首页 > 移动开发 > IOS开发

iOS时间选择器Demo(-)

2016-03-03 15:02 477 查看
@property (nonatomic,strong)UILabel *timeLabel;
@property (nonatomic,strong)UIDatePicker *loadDatePickerView;
定义时间选择器<span style="font-family: Arial, Helvetica, sans-serif;">loadDatePickerView,定义label来显示选择的时间</span>
<span style="font-family: Arial, Helvetica, sans-serif;">
</span>
<span style="font-family: Arial, Helvetica, sans-serif;"></span><pre name="code" class="objc">-(void)viewDidLoad{
UIButton *timebtn = [UIButton buttonWithType:UIButtonTypeCustom];
timebtn.frame = CGRectMake(100, 100, KMainWidth - 200, 50);
[timebtn setTitle:@"时间选择器" forState:UIControlStateNormal];
[timebtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[timebtn addTarget:self action:@selector(timeBtnAction) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:timebtn];

self.timeLabel = [[UILabel alloc]init];
self.timeLabel.frame = CGRectMake(100, 200, KMainWidth - 200, 50);
self.timeLabel.textAlignment = NSTextAlignmentCenter;
self.timeLabel.font = [UIFont systemFontOfSize:15];
self.timeLabel.textColor = [UIColor greenColor];
[self.view addSubview:self.timeLabel];

}

#pragma mark - timeBtnAction
-(void)timeBtnAction{
if (_loadDatePickerView == nil) {
_loadDatePickerView = [[UIDatePicker alloc] init];
//设置时区
_loadDatePickerView.locale = [NSLocale localeWithLocaleIdentifier:@"zh_CN"];
//设置时间模式
_loadDatePickerView.datePickerMode = UIDatePickerModeDateAndTime;

//设置最小时间(20年前)3秒
_loadDatePickerView.minimumDate = [NSDate dateWithTimeIntervalSinceNow:-(20 * 365 * 24 * 60 * 60)];
//设置最大时间(20年后)
_loadDatePickerView.maximumDate = [NSDate dateWithTimeIntervalSinceNow:(20 * 365 * 24 * 60 * 60)];
//设置时间间隔 设置的值必须能够被60整除
_loadDatePickerView.minuteInterval = 30;

//监听时间值改变
[_loadDatePickerView addTarget:self action:@selector(datePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
_loadDatePickerView.frame = CGRectMake(0, self.view.frame.size.height - 170, KMainWidth, 170);
[self.view addSubview:_loadDatePickerView];
}else{
self.loadDatePickerView.hidden = NO;
}

}

-(void)datePickerValueChanged:(UIDatePicker *)datePicker{

//获得时间
NSDate  *date = (datePicker == nil ? [NSDate date]:datePicker.date);
//格式化时间
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
//时间格式
formatter.dateFormat = @"yyyy-MM-dd EEE HH:mm";
//将时间转换成字符串
self.timeLabel.text = [formatter stringFromDate:date];

self.loadDatePickerView.hidden = YES;
}
实现的效果是:点击按钮,弹出时间选择器,选择完时间后,label显示时间,时间选择器自动隐藏。
效果图:
<img src="https://img-blog.csdn.net/20160303162950780?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="" />
<img src="https://img-blog.csdn.net/20160303163002717?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="" />



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios 时间选择器 日期