由于项目中要用到时间的选择,但是自带的datePicker感觉有点丑,并且它是不支持编辑的,所以我用UIPickerView做了日期选择器和时间选择器
在字体方面参考了网上的资料
效果图如下:
picker.gif- 制作思路其实很简单,日期选择器和时间选择器都是一个独立的UIViewController,如下图:
- 以日期选择器为例,xib文件如下:
- 随后将所有要操作的组件连线进控制器
- 创建数组,用于存储年份,月份,天数,其中天数会根据年份和天数变化,需要单独创建一个方法计算
- 初始化UIPickerView并且设置dataSource和delegate都是self
- 实现UIPickerView的数据源方法和代理方法
- 设置控制器的代理,让外界控制器实现按钮事件
- myDatePickerView.h
#import <UIKit/UIKit.h>
@protocol myDatePickerViewDelegate <NSObject>
@optional -(void)pressBackBtn;
@optional -(void)pressEnterBtn;
@end
@interface myDatePickerView : UIViewController
@property (nonatomic,strong) id<myDatePickerViewDelegate> delegate;
//包裹控件的view,与self.view上下左右保持着5dp
@property (weak, nonatomic) IBOutlet UIView *ParentView;
//我们的主角,pickerView
@property (strong, nonatomic) IBOutlet UIPickerView *pickerView;
//这三个参数放在外面,可供外界调用
@property (nonatomic,strong) NSString *year;
@property (nonatomic,strong) NSString *month;
@property (nonatomic,strong) NSString *day;
//创建一个将年月日组合起来的NSString,并返回
-(NSString *)getDateForMyMode;
@end
- myDatePickerView.m
#import "myDatePickerView.h"
@interface myDatePickerView ()<UIPickerViewDelegate,UIPickerViewDataSource>
@property (weak, nonatomic) IBOutlet UIButton *backBtn;
@property (weak, nonatomic) IBOutlet UIButton *enterBtn;
@property (weak, nonatomic) IBOutlet UILabel *DialogTitle;
//保存年月日数据的array
@property (nonatomic,strong) NSMutableArray *yearArray;
@property (nonatomic,strong) NSMutableArray *monthArray;
@property (nonatomic,strong) NSMutableArray *dayArray;
//选中的当前行
@property (nonatomic,assign) int selectedRowYear;
@property (nonatomic,assign) int selectedRowMonth;
@property (nonatomic,assign) int selectedRowDay;
////当前选中的列
//@property (nonatomic,assign) int selectComponent;
//每个月的天数
@property (nonatomic,assign) int dayNumber;
//应该跟新天数了,当月份或年份被选择过或是刚进入为true,需要刷新day
@property (nonatomic,assign) Boolean dayShouldChangeEnable;
@end
@implementation myDatePickerView
//pickerView的懒加载
-(UIPickerView *)pickerView{
if(!_pickerView){
_pickerView = [[UIPickerView alloc] init];
}
return _pickerView;
}
//年份的懒加载
-(NSMutableArray *)yearArray{
if(!_yearArray){
_yearArray = [NSMutableArray array];
//此处设置年份,固定的,当然你也可以提取出来,设为可变的
for (int index=2013; index<=2050; index++) {
[_yearArray addObject:[@(index) stringValue]];
}
}
return _yearArray;
}
//根据传递进入的dayNumber计算dayArray
-(void)setDaysForMonth:(int) dayNumber{
self.dayArray = nil;
self.dayArray = [NSMutableArray array];
for (int index=1; index<=_dayNumber; index++) {
[_dayArray addObject:[@(index) stringValue]];
}
}
//月份的懒加载
-(NSMutableArray *)monthArray{
if(!_monthArray){
_monthArray = [NSMutableArray array];
for (int index=1; index<=12; index++) {
[_monthArray addObject:[@(index) stringValue]];
}
}
return _monthArray;
}
//获取当期的年月日,并且初始化pickView,及一些其他参数
-(void)getDateOfThisMonment{
//获取当前的年月日
NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay;
NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:[NSDate date]];
int year = (int)[dateComponent year];
int month = (int)[dateComponent month];
int day = (int)[dateComponent day];
//我根据月份和年份计算天数
[self calculateDayWithMonth:month andYear:year];
//设置dataSource和delegate
self.pickerView.dataSource = self;
self.pickerView.delegate = self;
NSLog(@"%i,%i,%i",year,month,day);
self.selectedRowYear = (year-2013);
self.selectedRowMonth = (month -1);
self.selectedRowDay = (day-1);
//根据现在的年份和月份,初始化pickerView
[self.pickerView selectRow:_selectedRowYear inComponent:0 animated:YES];
[self.pickerView selectRow:_selectedRowMonth inComponent:1 animated:YES];
[self.pickerView selectRow:_selectedRowDay inComponent:2 animated:YES];
//将目前的日期赋值给公共参数,以便外面调用
self.year = [@(year) stringValue];
self.month = [@(month) stringValue];
self.day = [@(day) stringValue];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
self.view.alpha = 0.0f;
//获取当前的年月日,并且初始化
[self getDateOfThisMonment];
//边角弧度设置
[[self.view layer] setCornerRadius:15.0];
self.DialogTitle.text = @"日期选择器";
[self.backBtn setTitle:@"后退" forState:UIControlStateNormal];
[self.enterBtn setTitle:@"确定" forState:UIControlStateNormal];
//绑定按钮事件
[self.backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
[self.enterBtn addTarget:self action:@selector(enterClick) forControlEvents:UIControlEventTouchUpInside];
self.dayShouldChangeEnable= false;
}
//按下后退按键
-(void)backClick{
[self.delegate pressBackBtn];
}
//按下确定按键
-(void)enterClick{
[self.delegate pressEnterBtn];
}
/*********************数据源方法**********************/
//返回的是pickerView有多少列
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 3; // 年份、月份、天
}
//表明pickerView每列的行数
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
if(component == 0){ //年份行数
return self.yearArray.count;
}
else if(component == 1){ //月份行数
return self.monthArray.count;
}
else{ //天行数
return self.dayArray.count;
}
}
/*********************数据源方法**********************/
/*********************代理方法**********************/
//第row行的标题
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
if (component ==0) { //年份第row行标题
return [NSString stringWithFormat:@"%@年",[self.yearArray objectAtIndex:row]];
}else if(component == 1){ //月份第row行标题
return [NSString stringWithFormat:@"%@月",[self.monthArray objectAtIndex:row]];
}else{ //天数第row行标题
return [NSString stringWithFormat:@"%@日",[self.dayArray objectAtIndex:row]];
}
}
/*
监听用户选中第component列的第row行,在这个之中,读取被选中的年月日
因为年份和月份不同,天数都会时时改变,所以设置_dayShouldChangeEnable参数
表示当年份和月份改变时,重新计算天数,这里有点缺陷,就是可能存在重复计算天数的情况,影响效率
*/
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
//NSLog(@"month = %@,year=%@",);
if(component == 0){
//当用户更改年份的时候,为防止闰年和非闰年对2月份天数的影响,_dayShouldChangeEnable = true表明需要重新计算对应月份的天数
_dayShouldChangeEnable = true;
self.year = _yearArray[row];//将选中的月份数赋值给公共的年份参数,以便外面调用
self.selectedRowYear = (int)row; //将row赋值给
[pickerView reloadComponent:0]; //为了选中的row变颜色,需要刷新整行
}
else if(component==1){
//当用户更改月份的时候,_dayShouldChangeEnable = true表明需要重新计算天数
_dayShouldChangeEnable = true;
self.month = _monthArray[row]; //将选中的月份数赋值给公共的月份参数,以便外面调用
self.selectedRowMonth = (int)row;
[pickerView reloadComponent:1];
}
else{
self.day = _dayArray[row];//将选中的天数赋值给公共的天数参数,以便外面调用
NSLog(@"---------->>>>2");
self.selectedRowDay = (int)row;
[pickerView reloadComponent:2];
}
if(_dayShouldChangeEnable) //若,天数需要更新,那么执行
{
//调用计算天数的函数
[self calculateDayWithMonth:[self.month intValue] andYear:[self.year intValue]];
//由于更新的时候self.selectRowDay很可能大于 天数的最大值,比如self.selectRowDay为31,而天数最大值切换至了29,所以若超出,则需要将selectRowDay重新赋值
if(self.selectedRowDay > _dayNumber-1){
self.selectedRowDay = _dayNumber-1;
NSLog(@"---------->>>>>%zi<<<<<<",self.selectedRowDay);
}
//重新对天数的那一列进行更新
[pickerView reloadComponent:2];
//false
_dayShouldChangeEnable = false;
}
}
//选中的项目变成绿色
-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
UILabel* Label = (UILabel*)view;
if (!Label){
Label = [[UILabel alloc] init];
Label.minimumScaleFactor = 8;
Label.adjustsFontSizeToFitWidth = YES;
[Label setTextAlignment:NSTextAlignmentCenter];
[Label setFont:[UIFont systemFontOfSize:15]];
//当年份列,被选中的行对应变成绿色
if (component==0&&_selectedRowYear==row) {
Label.textColor=[UIColor greenColor];
}else if (component==1&&_selectedRowMonth==row){
Label.textColor= [UIColor greenColor];
}else if(component==2&&_selectedRowDay==row){
Label.textColor= [UIColor greenColor];
}
}
Label.text=[self pickerView:pickerView titleForRow:row forComponent:component];
return Label;
}
/*********************代理方法**********************/
//根据month和year计算对应的天数
-(void)calculateDayWithMonth:(int) month andYear:(int) year{
float yearF = [self.year floatValue]/4; //能被4整除的是闰年
float yearI = (int)yearF; //若yearI和yearF不一样,也就是说没有被整除,则不是闰年
//当然以上计算没有包括:能被100整除,但不能被400整除的,不是闰年,因为2000年已过2100年还远....
switch (month) {
case 1:_dayNumber = 31; break;
case 2:
if(yearF != yearI){_dayNumber = 28;}else{
_dayNumber = 29;}break;
case 3:_dayNumber = 31;break;
case 4:_dayNumber = 30;break;
case 5:_dayNumber = 31;break;
case 6:_dayNumber = 30;break;
case 7:_dayNumber = 31;break;
case 8:_dayNumber = 31;break;
case 9:_dayNumber = 30;break;
case 10:_dayNumber = 31;break;
case 11:_dayNumber = 30;break;
case 12:_dayNumber = 31;break;
default:_dayNumber = 31;break;
}
[self setDaysForMonth:_dayNumber]; //此处调用函数,将dayArray重新赋值;
}
//将日期格式转化为2016-01-01这种格式
-(NSString *)getDateForMyMode{
NSString *myMonth = @"";
NSString *myDay = @"";
if([self.month intValue] < 10){
myMonth = [NSString stringWithFormat:@"0%@",self.month];
}else{
myMonth = [NSString stringWithFormat:@"%@",self.month];
}
if([self.day intValue] <10){
myDay = [NSString stringWithFormat:@"0%@",self.day];
}else{
myDay = [NSString stringWithFormat:@"%@",self.day];
}
return [NSString stringWithFormat:@"%@-%@-%@",self.year,myMonth,myDay];
}
-(void)dealloc{
NSLog(@"myDatePickerView dealloc");
}
@end
-
myTimePickerView.h和myTimePickerView.m类似,这里就不贴了....
-
最后来看下主控制器,值得注意的是我创建了一个coverView,用来在日期(时间)选择器弹出的时候,覆盖主控制器的view,让用户无法在弹出状态按到主控制器的view中的按钮,由于ViewController.h中啥都没有,所以只贴ViewController.m
-
ViewController.m :
#import "ViewController.h"
#import "myDatePickerDialog.h"
#import "myDatePickerView.h"
#import "myTimePickerView.h"
@interface ViewController ()<myDatePickerViewDelegate,myTimePickerViewDelegate>
@property (nonatomic,strong) myDatePickerDialog *datePickerDialog;
@property (nonatomic,strong) myDatePickerView *datePickerView;
@property (nonatomic,strong) myTimePickerView *timePickerView;
@property (weak, nonatomic) IBOutlet UIButton *setDate;
@property (weak, nonatomic) IBOutlet UIButton *setTime;
//遮盖view
@property (nonatomic,strong) UIView *coverView;
@end
@implementation ViewController
//使用datePickerDialog 懒加载,没用到
-(myDatePickerDialog *)datePickerDialog{
if(!_datePickerDialog){
self.datePickerDialog = [[myDatePickerDialog alloc] init];
}
return _datePickerDialog;
}
-(UIView *)coverView{
if(!_coverView){
_coverView = [[UIView alloc] initWithFrame:self.view.frame];
_coverView.backgroundColor = [UIColor blackColor];
_coverView.alpha = 0.3;
}
return _coverView;
}
//日期选择器懒加载
-(myDatePickerView *)datePickerView{
if(!_datePickerView){
self.datePickerView = [[myDatePickerView alloc] init];
self.datePickerView.delegate = self;
}
return _datePickerView;
}
//时间选择器懒加载
-(myTimePickerView *)timePickerView{
if(!_timePickerView){
_timePickerView = [[myTimePickerView alloc] init];
_timePickerView.delegate = self;
}
return _timePickerView;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//使用datePicker第一步,设置datePickerMode,默认状态下是UIDatePickerModeDateAndTime
// self.datePicker.datePickerMode = UIDatePickerModeDateAndTime;
//第二步,设置其他细节问题,入最早时间,最迟时间等等,目前没有设置,跳骨
[self.setDate addTarget:self action:@selector(showDateView) forControlEvents:UIControlEventTouchUpInside];
[self.setTime addTarget:self action:@selector(showTimeView) forControlEvents:UIControlEventTouchUpInside];
}
//显示日期选择器
-(void)showDateView{
CGRect tmp = self.datePickerView.view.frame;
CGFloat xView = self.view.center.x;
CGFloat yView = self.view.center.y;
tmp.origin.x = xView - self.datePickerView.view.frame.size.width/2;
tmp.origin.y = yView - self.datePickerView.view.frame.size.height/2;
_datePickerView.view.frame = tmp;
[UIView animateWithDuration:0.5 animations:^{
self.datePickerView.view.alpha = 1.0;
}];
[self.view addSubview:self.coverView];
[self.view addSubview:self.datePickerView.view];
}
//显示时间选择器
-(void)showTimeView{
CGRect tmp = self.timePickerView.view.frame;
CGFloat xView = self.view.center.x;
CGFloat yView = self.view.center.y;
tmp.origin.x = xView - self.timePickerView.view.frame.size.width/2;
tmp.origin.y = yView - self.timePickerView.view.frame.size.height/2;
_timePickerView.view.frame = tmp;
[UIView animateWithDuration:0.5 animations:^{
self.timePickerView.view.alpha = 1.0;
}];
[self.view addSubview:self.coverView];
[self.view addSubview:self.timePickerView.view];
}
/***********myDatePickerView的代理**********/
- (void)pressEnterBtn{
[self.setDate setTitle:[self.datePickerView getDateForMyMode] forState:UIControlStateNormal];
[UIView animateWithDuration:0.5 animations:^{
[self.coverView removeFromSuperview];
self.datePickerView.view.alpha = 0.0;
} completion:^(BOOL finished) {
[self.datePickerView.view removeFromSuperview];
//[self.coverView removeFromSuperview];
}];
//self.datePickerView = nil;
}
-(void)pressBackBtn{
[UIView animateWithDuration:0.5 animations:^{
self.datePickerView.view.alpha = 0.0;
[self.coverView removeFromSuperview];
} completion:^(BOOL finished) {
[self.datePickerView.view removeFromSuperview];
//[self.coverView removeFromSuperview];
}];
//self.datePickerView = nil;
}
/***********myDatePickerView的代理**********/
/***********myTimePickerView的代理**********/
- (void)pressEnterBtn_time{
[self.setTime setTitle:[self.timePickerView getTimeForMyMode] forState:UIControlStateNormal];
[UIView animateWithDuration:0.5 animations:^{
self.timePickerView.view.alpha = 0.0;
[self.coverView removeFromSuperview];
} completion:^(BOOL finished) {
[self.timePickerView.view removeFromSuperview];
//[self.coverView removeFromSuperview];
}];
//self.datePickerView = nil;
}
-(void)pressBackBtn_time{
[UIView animateWithDuration:0.5 animations:^{
[self.coverView removeFromSuperview];
self.timePickerView.view.alpha = 0.0;
} completion:^(BOOL finished) {
[self.timePickerView.view removeFromSuperview];
}];
//self.datePickerView = nil;
}
/***********myTimePickerView的代理**********/
@end
网友评论
为什么不直接附上git地址呢?