简易DatePickerView

仿了一个DatePickerView,使用就在响应方法里面初始化就好.代码直接贴在下面了


TimePickerView.h

#import 

typedef enum: NSUInteger {

    DatePickerViewDateTimeModel,//年月日时分

    DatePickerViewDateModel,//年月日

    DatePickerViewTimeModel,//时分

} DatePickerViewModel;

NS_ASSUME_NONNULL_BEGIN

@protocolTimePickerViewDelegate

//确定按钮

- (void)didClickFinishDateTimePickerView:(NSString*)date;

//取消按钮

- (void)didClickCancelTimePickerView;

@end

@interfaceTimePickerView :UIView

/** 协议 */

@property (nonatomic, weak) id<TimePickerViewDelegate>delegate;

//当前时间

@property (nonatomic, strong) NSDate *currentDate;

//标题中心文字

@property (nonatomic, strong) UILabel *titleLabel;

//时间选择器模式

@property (nonatomic, assign) DatePickerViewModel pickerViewModel;

//隐藏

- (void)hideTimePickerView;

//显示

- (void)showTimePickerView;

@end


TimePickerView.m

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width

#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue &0xFF0000) >>16))/255.0green:((float)((rgbValue &0xFF00) >>8))/255.0blue:((float)(rgbValue &0xFF))/255.0alpha:1.0]

//获取RGB颜色

#define RGBA(r,g,b,a) [UIColor colorWithRed:(r)/255.0fgreen:(g)/255.0fblue:(b)/255.0falpha:a]

@interface TimePickerView ()<UIPickerViewDelegate,UIPickerViewDataSource>

{

    NSInteger yearRange;

    NSInteger dayRange;

    NSInteger startYear;

    NSInteger selectedYear;

    NSInteger selectedMonth;

    NSInteger selectedDay;

    NSInteger selectedHour;

    NSInteger selectedMinute;

    NSInteger selectedSecond;

    NSCalendar *calendar;

    //左边按钮

    UIButton *cancelButton;

    //右边按钮

    UIButton *chooseButton;

}

/** 选择器 */

@property (nonatomic, strong) UIPickerView *pickerView;

/** 选择器内容 */

@property (nonatomic, copy) NSString *string;

@property (nonatomic, strong) UIView *contentV;

@property (nonatomic, strong) UIView *bgView;

@end

@implementationTimePickerView

- (instancetype)initWithFrame:(CGRect)frame

{

    if(self= [super initWithFrame:frame]) {

        self.backgroundColor=RGBA(0,0,0,0.5);

        self.alpha=0;

        UIView *contentV = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 220)];

        contentV.backgroundColor = UIColor.whiteColor;

        [self addSubview:contentV];

        self.contentV= contentV;


        self.pickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 40, [UIScreen mainScreen].bounds.size.width, 180)];

        self.pickerView.backgroundColor = UIColor.whiteColor;

        self.pickerView.delegate=self;

        self.pickerView.dataSource=self;

        [contentV addSubview:self.pickerView];


        //选择器上方view

        UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 40)];

        topView.backgroundColor = UIColor.whiteColor;

        [contentV addSubview:topView];

        //取消按钮

        cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];

        cancelButton.frame=CGRectMake(12,0,40,40);

        [cancelButton setTitle:@"取消" forState:UIControlStateNormal];

        [cancelButton setTitleColor:UIColorFromRGB(0x0d8bf5) forState:UIControlStateNormal];

        [cancelButton addTarget:self action:@selector(cancelButtonClick) forControlEvents:UIControlEventTouchUpInside];

        [topView addSubview:cancelButton];

        //确定按钮

        chooseButton = [UIButton buttonWithType:UIButtonTypeCustom];

        chooseButton.frame = CGRectMake([UIScreen mainScreen].bounds.size.width-52, 0, 40, 40);

        [chooseButton setTitle:@"确定" forState:UIControlStateNormal];

        [chooseButton setTitleColor:UIColorFromRGB(0x0d8bf5) forState:UIControlStateNormal];

        [chooseButton addTarget:self action:@selector(chooseButtonClick) forControlEvents:UIControlEventTouchUpInside];

        [topView addSubview:chooseButton];


        self.titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(cancelButton.frame), 0, SCREEN_WIDTH-104, 40)];

        [topView addSubview:self.titleLabel];

        _titleLabel.textColor=UIColorFromRGB(0x3f4548);

        _titleLabel.font = [UIFont systemFontOfSize:13];

        _titleLabel.textAlignment = NSTextAlignmentCenter;

        //分割线

        UIView *splitView = [[UIView alloc]initWithFrame:CGRectMake(0, 40, [UIScreen mainScreen].bounds.size.width, 0.5)];

        splitView.backgroundColor=UIColorFromRGB(0xe6e6e6);

        [topView addSubview:splitView];

        NSCalendar *calendar0 = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

        NSDateComponents *comps = [[NSDateComponents alloc]init];

        NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute;

        comps = [calendar0 components:unitFlags fromDate:[NSDate date]];

        NSInteger year = [compsyear];

        startYear= year -15;

        yearRange=50;

        [self setCurrentDate:[NSDate date]];

    }

    return self;

}

#pragma mark UIPickerViewDataSource

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView*)pickerView

{

    if (self.pickerViewModel == DatePickerViewDateTimeModel) {

        return5;

    }else if (self.pickerViewModel == DatePickerViewDateModel) {

        return3;

    }else if (self.pickerViewModel == DatePickerViewTimeModel) {

        return2;

    }

    return0;

}

//每列返回的内容

-(NSInteger)pickerView:(UIPickerView*)pickerView numberOfRowsInComponent:(NSInteger)component

{

    if (self.pickerViewModel == DatePickerViewDateTimeModel) {

        switch(component) {

            case 0:

                return yearRange;

                break;

            case1:

                return 12;

                break;

            case 2:

                return dayRange;

                break;

            case 3:

                return 24;

                break;

            case 4:

                return 60;

                break;

            default:

                break;

        }

    }else if (self.pickerViewModel == DatePickerViewDateModel){

        switch(component) {

            case 0:

                return yearRange;

                break;

            case 1:

                return 12;

                break;

            case 2:

                return dayRange;

                break;

            default:

                break;

        }

    }else if (self.pickerViewModel == DatePickerViewTimeModel){

        switch(component) {

            case 0:

                return 24;

                break;

            case 1:

                return 60;

                break;

            default:

                break;

        }

    }

    return 0;

}

#pragma mark UIPickerViewDelegate

//默认时间处理

- (void)setCurrentDate:(NSDate*)currentDate{

    //获取当前时间

    NSCalendar *calendar0 = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSDateComponents *comps = [[NSDateComponents alloc]init];

    NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute;

    comps = [calendar0 components:unitFlags fromDate:[NSDate date]];

    NSInteger year = [comps year];

    NSInteger month = [comps month];

    NSInteger day = [comps day];

    NSInteger hour = [comps hour];

    NSInteger minute = [comps minute];

    selectedYear= year;

    selectedMonth= month;

    selectedDay= day;

    selectedHour= hour;

    selectedMinute= minute;

    dayRange = [self isAllDay:year andMonth:month];

    if (self.pickerViewModel == DatePickerViewDateTimeModel) {

        [self.pickerView selectRow:year-startYear inComponent:0 animated:NO];

        [self.pickerView selectRow:month-1 inComponent:1 animated:NO];

        [self.pickerView selectRow:day-1 inComponent:2 animated:NO];

        [self.pickerView selectRow:hour inComponent:3 animated:NO];

        [self.pickerView selectRow:minute inComponent:4 animated:NO];

        [self pickerView:self.pickerView didSelectRow:year-startYear inComponent:0];

        [self pickerView:self.pickerView didSelectRow:month-1 inComponent:1];

        [self pickerView:self.pickerView didSelectRow:day-1 inComponent:2];

        [self pickerView:self.pickerView didSelectRow:hour inComponent:3];

        [self pickerView:self.pickerView didSelectRow:minute inComponent:4];


    }else if (self.pickerViewModel == DatePickerViewDateModel) {

        [self.pickerView selectRow:year-startYear inComponent:0 animated:NO];

        [self.pickerView selectRow:month-1 inComponent:1 animated:NO];

        [self.pickerView selectRow:day-1 inComponent:2 animated:NO];

        [self pickerView:self.pickerView didSelectRow:year-startYear inComponent:0];

        [self pickerView:self.pickerView didSelectRow:month-1 inComponent:1];

        [self pickerView:self.pickerView didSelectRow:day-1 inComponent:2];


    }else if (self.pickerViewModel == DatePickerViewTimeModel) {

        [self.pickerView selectRow:hour inComponent:0 animated:NO];

        [self.pickerView selectRow:minute inComponent:1 animated:NO];

        [self pickerView:self.pickerView didSelectRow:hour inComponent:0];

        [self pickerView:self.pickerView didSelectRow:minute inComponent:1];

    }

    [self.pickerView reloadAllComponents];

}

- (UIView*)pickerView:(UIPickerView*)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView*)view

{

    UILabel*label = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH* component/6.0,0,SCREEN_WIDTH/6.0,30)];

    label.font = [UIFont systemFontOfSize:15.0];

    label.tag= component*100+row;

    label.textAlignment = NSTextAlignmentCenter;

    if (self.pickerViewModel == DatePickerViewDateTimeModel) {

        switch(component) {

            case 0:

            {

                label.text= [NSStringstringWithFormat:@"%ld年",(long)(startYear+ row)];

            }

                break;

            case 1:

            {

                label.text= [NSStringstringWithFormat:@"%ld月",(long)row+1];

            }

                break;

            case 2:

            {

                label.text= [NSStringstringWithFormat:@"%ld日",(long)row+1];

            }

                break;

            case 3:

            {

                label.textAlignment = NSTextAlignmentRight;

                label.text= [NSStringstringWithFormat:@"%ld时",(long)row];

            }

                break;

            case 4:

            {

                label.textAlignment = NSTextAlignmentRight;

                label.text= [NSStringstringWithFormat:@"%ld分",(long)row];

            }

                break;

            default:

                break;

        }

    }else if (self.pickerViewModel == DatePickerViewDateModel) {

        switch(component) {

            case 0:

                {

                    label.text= [NSStringstringWithFormat:@"%ld年",(long)(startYear+ row)];

                }

                break;

            case 1:

                {

                    label.text= [NSStringstringWithFormat:@"%ld月",(long)(row+1)];

                }

                break;

            case 2:

                {

                    label.text= [NSStringstringWithFormat:@"%ld日",(long)(row+1)];

                }

                break;

            default:

                break;

        }

    }else if (self.pickerViewModel == DatePickerViewTimeModel) {

        switch(component) {

            case 0:

            {

                label.text= [NSStringstringWithFormat:@"%ld时",(long)(row)];

            }

                break;

            case 1:

            {

                label.text= [NSStringstringWithFormat:@"%ld分",(long)(row)];

            }

                break;

            default:

                break;

        }

    }

    returnlabel;

}

//选择内容的宽

- (CGFloat)pickerView:(UIPickerView*)pickerView widthForComponent:(NSInteger)component

{

    if (self.pickerViewModel == DatePickerViewDateTimeModel) {

        return ([UIScreen mainScreen].bounds.size.width-40)/5;

    }else if (self.pickerViewModel == DatePickerViewDateModel) {

        return ([UIScreen mainScreen].bounds.size.width-40)/3;

    }else if (self.pickerViewModel == DatePickerViewTimeModel) {

        return ([UIScreen mainScreen].bounds.size.width-40)/2;

    }

    return0;

}

//内容的高

- (CGFloat)pickerView:(UIPickerView*)pickerView rowHeightForComponent:(NSInteger)component

{

    return 30;

}

// 监听picker的滑动

- (void)pickerView:(UIPickerView*)pickerView

      didSelectRow:(NSInteger)row inComponent:(NSInteger)component {

    if (self.pickerViewModel == DatePickerViewDateTimeModel) {

        switch(component) {

            case 0:

            {

                selectedYear=startYear+ row;

                dayRange=[self isAllDay:selectedYear andMonth:selectedMonth];

                [self.pickerView reloadComponent:2];

            }

                break;

            case 1:

            {

                selectedMonth=row+1;

                dayRange=[self isAllDay:selectedYear andMonth:selectedMonth];

                [self.pickerView reloadComponent:2];

            }

                break;

            case 2:

            {

                selectedDay=row+1;

            }

                break;

            case 3:

            {

                selectedHour=row;

            }

                break;

            case 4:

            {

                selectedMinute=row;

            }

                break;

            default:

                break;

        }

        _string =[NSString stringWithFormat:@"%ld-%.2ld-%.2ld %.2ld:%.2ld",selectedYear,selectedMonth,selectedDay,selectedHour,selectedMinute];

    }else if (self.pickerViewModel == DatePickerViewDateModel){

        switch(component) {

            case 0:

            {

               selectedYear=startYear+ row;

               dayRange=[self isAllDay:selectedYear andMonth:selectedMonth];

               [self.pickerViewreloadComponent:2];

            }

                break;

            case 1:

            {

                selectedMonth=row+1;

                dayRange=[self isAllDay:selectedYear andMonth:selectedMonth];

                [self.pickerView reloadComponent:2];

            }

                break;

            case 2:

            {

               selectedDay=row+1;

            }

                break;

            default:

                break;

            }

        _string =[NSString stringWithFormat:@"%ld-%.2ld-%.2ld",selectedYear,selectedMonth,selectedDay];

    }else if (self.pickerViewModel == DatePickerViewTimeModel){

        switch(component) {

            case 0:

            {

                selectedHour=row;

            }

                break;

            case 1:

            {

                selectedMinute=row;

            }

                break;

            default:

                break;

        }

        _string =[NSString stringWithFormat:@"%.2ld:%.2ld",selectedHour,selectedMinute];

    }

}

#pragma mark Show Or Hidden

- (void)showTimePickerView

{

    [self setCurrentDate:[NSDate date]];

    __weak typeof(self)weakSelf = self;

    self.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);

    [UIView animateWithDuration:0.25f animations:^{

        self.alpha=1;

        weakSelf.contentV.frame=CGRectMake(0,SCREEN_HEIGHT-220,SCREEN_WIDTH,220);

    }completion:^(BOOLfinished) {


    }];

}

- (void)hideTimePickerView

{

    __weak typeof(self)weakSelf = self;

    [UIView animateWithDuration:0.25f animations:^{

        self.alpha=0;

        weakSelf.contentV.frame=CGRectMake(0,SCREEN_HEIGHT,SCREEN_WIDTH,220);

    }completion:^(BOOLfinished) {

        self.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT);

    }];

}

#pragma mark -- private

//取消方法

- (void)cancelButtonClick{

    if(self.delegate!=nil&& [self.delegaterespondsToSelector:@selector(didClickCancelTimePickerView)]) {

        [self.delegate didClickCancelTimePickerView];

    }

    [self hideTimePickerView];

}

//选中方法

- (void)chooseButtonClick{

    if(self.delegate!=nil&& [self.delegaterespondsToSelector:@selector(didClickFinishDateTimePickerView:)]) {

        [self.delegate didClickFinishDateTimePickerView:_string];

    }

    [self hideTimePickerView];

}

//每月天数

- (NSInteger)isAllDay:(NSInteger)year andMonth:(NSInteger)month{

    intday =0;

    //1、3、5、7、8、10、12月31天

    switch(month) {

        case1:

        case3:

        case5:

        case7:

        case8:

        case10:

        case12:

            day =31;

            break;

    //2、4、5、6、11月30天

        case4:

        case6:

        case9:

        case11:

            day =30;

            break;

    //判断平年闰年二月天数

        case2:

        {

            if(((year%4==0)&&(year%100!=0))||(year%400==0)) {

                day =29;

                break;

            }else{

                day =28;

                break;

            }

        }

        default:

            break;

    }

    returnday;

}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event

{

    [self hideTimePickerView];

}

@end

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,547评论 6 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,399评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,428评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,599评论 1 274
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,612评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,577评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,941评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,603评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,852评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,605评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,693评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,375评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,955评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,936评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,172评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,970评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,414评论 2 342

推荐阅读更多精彩内容