自定义UIDatePickerView

因为项目中需要使用到时间选择器,需求是最大只能选择当天,超过当前天的日期不显示,系统的无法满足需求,如是自己定义了一个时间选择器,废话不多说,效果如下:
IMG_0894.GIF

.h文件

@interface P_TDatePickerView : UIPickerView

@property (nonatomic ,assign)NSInteger year;///当前年

@property (nonatomic ,assign)NSInteger month;///当前月

@property (nonatomic ,assign)NSInteger day;///当前日

@property (nonatomic ,assign)NSInteger monthRow;

@property (nonatomic ,assign)NSInteger dayRow;

@property (nonatomic ,strong)NSArray * yearArray;///年份数组

@property (nonatomic ,strong)NSArray * monthArray;///月份数组

@property (nonatomic ,strong)NSArray * dateArray;///日期数组

@property (nonatomic, assign) NSInteger state;///1、从中间某个时间段展示

@property (nonatomic, strong) NSString * date;///需要展示的年月e日

///选中的行,手动滑动

-(void)P_TDatePickerView:(P_TDatePickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component;

- (UIView*)P_TDatePickerView:(P_TDatePickerView*)pickerViewviewForRow:(NSInteger)rowforComponent:(NSInteger)componentreusingView:(UIView*)view;

///刷新数据

- (void)P_TReloadAllData;

@end

.m文件

#import "P_TDatePickerView.h"

@interface P_TDatePickerView()

@end

@implementation P_TDatePickerView

- (void)awakeFromNib{
    [super awakeFromNib];

    if (self) {
        //获取当前年月日
        NSDate * date = [NSDate date];
        NSDateFormatter * matter = [[NSDateFormatter alloc] init];
        [matter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
        NSString *dateStr;
        dateStr=[matter stringFromDate:date];
        NSArray * array = [dateStr componentsSeparatedByString:@" "];
        if (array.count == 2) {
            NSString * string = array[0];
            NSArray * dateArray = [string componentsSeparatedByString:@"-"];
            if (dateArray.count == 3) {
                self.year = [dateArray[0] integerValue];
                self.month = [dateArray[1] integerValue];
                self.day = [dateArray[2] integerValue];
            }
        }
        NSMutableArray * dateArray = [[NSMutableArray alloc] init];
        for (int i = 1; i<32; i++) {
            if (i<10) {
                [dateArray addObject:[NSString stringWithFormat:@"0%d",i]];
            }else{
                [dateArray addObject:[NSString stringWithFormat:@"%d",i]];
            }
        }
        self.dateArray = dateArray;
        self.dayRow = self.day;
//        self.dayRow = 31;//从最小年份开始
        NSMutableArray * monthArray = [[NSMutableArray alloc] init];
        for (int i = 1; i<13; i++) {
            if (i<10) {
                [monthArray addObject:[NSString stringWithFormat:@"0%d",i]];
            }else{
                [monthArray addObject:[NSString stringWithFormat:@"%d",i]];
            }
        }
        self.monthArray = monthArray;
        self.monthRow = self.month;//从最新年份开始
//        self.monthRow = 12;//从最小年份开始
    }
}
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        //获取当前年月日
        NSDate * date = [NSDate date];
        NSDateFormatter * matter = [[NSDateFormatter alloc] init];
        [matter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
        NSString *dateStr;
        dateStr=[matter stringFromDate:date];
        NSArray * array = [dateStr componentsSeparatedByString:@" "];
        if (array.count == 2) {
            NSString * string = array[0];
            NSArray * dateArray = [string componentsSeparatedByString:@"-"];
            if (dateArray.count == 3) {
                self.year = [dateArray[0] integerValue];
                self.month = [dateArray[1] integerValue];
                self.day = [dateArray[2] integerValue];
            }
        }
        NSMutableArray * yearArray = [[NSMutableArray alloc] init];
        for (int i = (int)self.year -99; i <= self.year; i++) {
            [yearArray addObject:[NSString stringWithFormat:@"%d",i]];
        }
        self.yearArray = yearArray;
        
        NSMutableArray * dateArray = [[NSMutableArray alloc] init];
        for (int i = 1; i<32; i++) {
            if (i<10) {
                [dateArray addObject:[NSString stringWithFormat:@"0%d",i]];
            }else{
                [dateArray addObject:[NSString stringWithFormat:@"%d",i]];
            }
        }
        self.dateArray = dateArray;
        self.dayRow = 31;
        NSMutableArray * monthArray = [[NSMutableArray alloc] init];
        for (int i = 1; i<13; i++) {
            if (i<10) {
                [monthArray addObject:[NSString stringWithFormat:@"0%d",i]];
            }else{
                [monthArray addObject:[NSString stringWithFormat:@"%d",i]];
            }
        }
        self.monthArray = monthArray;
        self.monthRow = 12;
    }
    UIView * line = [[UIView alloc] initWithFrame:CGRectMake(0, 39, frame.size.width, 1.0)];
    line.backgroundColor = MainColor;
    [self addSubview:line];
    UIView * line1 = [[UIView alloc] initWithFrame:CGRectMake(0, 80, frame.size.width, 1.0)];
    line1.backgroundColor = MainColor;
    [self addSubview:line1];
    return self;
}

#pragma mark ===============刷新数据,确认当前每列返回的行数===============
- (void)P_TReloadAllData{
    if ([self.yearArray[[self selectedRowInComponent:0]] integerValue] == self.year) {//年份相同
        self.monthRow = self.month;//从最新年份开始
        if ([self.monthArray[[self selectedRowInComponent:1]] integerValue] == self.month) {
            self.dayRow = self.day;
        }else{
            self.dayRow = [P_TDatePickerView returnDayRowWithSKDatePickerView:[self.monthArray[[self selectedRowInComponent:1]] integerValue] currentDay:31 isLeapYear:[self isLeapYear:[self.yearArray[[self selectedRowInComponent:0]] integerValue]]];
        }
    }else{
        self.monthRow = 12;
        self.dayRow = [P_TDatePickerView returnDayRowWithSKDatePickerView:[self.monthArray[[self selectedRowInComponent:1]] integerValue] currentDay:31 isLeapYear:[self isLeapYear:[self.yearArray[[self selectedRowInComponent:0]] integerValue]]];
    }
    [self reloadAllComponents];
}

#pragma mark ===============返回样式===============
- (UIView *)P_TDatePickerView:(P_TDatePickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    CGFloat pkViewWidth = pickerView.frame.size.width;
    if (!view){
        view = [[UIView alloc] init];
    }
    UILabel *text = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, pkViewWidth/3.0, 40)];
    text.textAlignment = NSTextAlignmentCenter;
    switch (component) {
        case 0:{
            text.text = [NSString stringWithFormat:@"%@",pickerView.yearArray[row]];
        }
            break;
        case 1:{
            text.text = [NSString stringWithFormat:@"%@",pickerView.monthArray[row]];
        }
            break;
        default:{
            text.text = [NSString stringWithFormat:@"%@",pickerView.dateArray[row]];
        }
            break;
    }
    text.textAlignment = NSTextAlignmentCenter;
    [view addSubview:text];
    return view;
}
//选中的行,手动滑动
-(void)P_TDatePickerView:(P_TDatePickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    P_TDatePickerView * dpickerView = (P_TDatePickerView *)pickerView;
    switch (component) {
        case 0:{
            if ([dpickerView.yearArray[row] integerValue] == dpickerView.year) {
                //判断是否是当前年
                //当前年,刷新月份,如果选中的月份大于当前月份,则取当前月份,反之不滑动
                dpickerView.monthRow = dpickerView.month;//限定月份返回的行数
                [pickerView reloadComponent:1];
                if ([dpickerView selectedRowInComponent:1] >= dpickerView.month-1) {
                    dpickerView.dayRow = [P_TDatePickerView returnDayRowWithSKDatePickerView:dpickerView.month currentDay:self.day isLeapYear:[dpickerView isLeapYear:[dpickerView.yearArray[row] integerValue]]];
                }else{
                    dpickerView.dayRow = [P_TDatePickerView returnDayRowWithSKDatePickerView:[dpickerView.monthArray[[dpickerView selectedRowInComponent:1]] integerValue] currentDay:31 isLeapYear:[dpickerView isLeapYear:[dpickerView.yearArray[row] integerValue]]];
                }
                [pickerView reloadComponent:2];
                
            }else{
                dpickerView.dayRow = [P_TDatePickerView returnDayRowWithSKDatePickerView:[dpickerView.monthArray[[dpickerView selectedRowInComponent:1]] integerValue] currentDay:31 isLeapYear:[dpickerView isLeapYear:[dpickerView.yearArray[row] integerValue]]];
                dpickerView.monthRow = 12;
                [pickerView reloadComponent:1];
                [pickerView reloadComponent:2];
            }
        }
            break;
        case 1:{
            NSInteger dayrow;
            if ([dpickerView.yearArray[[dpickerView selectedRowInComponent:0]] integerValue]== dpickerView.year) {
                //判断是否当前年份
                //当前月,刷新日期,如果选中的日期大于当前日期,则取当前日期,反之不滑动
                if ([dpickerView.monthArray[row] integerValue] == dpickerView.month) {
                    //判断选中月份天数
                    dayrow = [P_TDatePickerView returnDayRowWithSKDatePickerView:dpickerView.month currentDay:self.day isLeapYear:[dpickerView isLeapYear:[dpickerView.yearArray[[dpickerView selectedRowInComponent:0]] integerValue]]];
                }else{
                    //判断选中月份天数
                    dayrow = [P_TDatePickerView returnDayRowWithSKDatePickerView:[dpickerView.monthArray[row] integerValue] currentDay:31 isLeapYear:[dpickerView isLeapYear:[dpickerView.yearArray[[dpickerView selectedRowInComponent:0]] integerValue]]];
                }
            }else{
                //判断选中月份天数
                dayrow = [P_TDatePickerView returnDayRowWithSKDatePickerView:[dpickerView.monthArray[row] integerValue] currentDay:31 isLeapYear:[dpickerView isLeapYear:[dpickerView.yearArray[[dpickerView selectedRowInComponent:0]] integerValue]]];
            }
            dpickerView.dayRow = dayrow;
            [pickerView reloadComponent:2];
        }
            break;
        default:
            break;
    }
}
#pragma mark ===============剥离判断日期返回行数的方法===============
/**
 返回天数的行数
 @param month 判断月份
 @param currentDay 对比的天数
 @param isleapYear 是否闰年
 @return 返回天数
 */
+ (NSInteger)returnDayRowWithSKDatePickerView:(NSInteger )month currentDay:(NSInteger)currentDay isLeapYear:(BOOL)isleapYear{
    NSInteger dayrow;
    //判断月份
    if (month == 2) {
        if (isleapYear) {
            dayrow = MIN(currentDay, 29);
        }else{
            dayrow = MIN(currentDay, 28);
        }
    }else if(month == 4||month == 6||month == 9||month == 11){
        dayrow = MIN(currentDay, 30);
    }else{
        dayrow = currentDay;
    }
    return dayrow;
}
#pragma mark ===============是否是闰年===============
- (BOOL)isLeapYear:(NSInteger)year{
    if(year%400 == 0||(year %100 != 0&&year%4 == 0)){
        return YES;
    }else{
        return NO;
    }
}
@end

可以xib 也可以代码布局,布局就不多说
主要是实现代理方法,代码如下:

#pragma mark ===============pickerViewDelegate===============
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 3;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    P_TDatePickerView * dpickView = (P_TDatePickerView *)pickerView;
    NSInteger row;
    switch (component) {
        case 0:
            row = [dpickView.yearArray count];
            break;
        case 1:
            row = dpickView.monthRow;
            break;
        case 2:
            row = dpickView.dayRow;
            break;
        default:
            return 0;
            break;
    }
    return row;
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    return 40;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    P_TDatePickerView * dpickView = (P_TDatePickerView *)pickerView;
    return [dpickView P_TDatePickerView:dpickView viewForRow:row forComponent:component reusingView:view];
}

详细代码传送门
http://code.cocoachina.com/view/1000458

如果正好可以解决您的需求,麻烦动动你的小手,给个Star。
如有疑问,可联系qq734651142

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

推荐阅读更多精彩内容