iOS自定义UIDatepicker日期选择器视图分享
程序员文章站
2023-12-15 23:56:28
由于项目需要,需要定制一个日期选择器,找了半天没找到合适的就自己写了个demo
自定义uidatepicker日期选择器视图
效果如下:
下面贴上相关代码:...
由于项目需要,需要定制一个日期选择器,找了半天没找到合适的就自己写了个demo
自定义uidatepicker日期选择器视图
效果如下:
下面贴上相关代码:
viewcontroller:
<pre name="code" class="objc">- (void)viewdidload { [super viewdidload]; // do any additional setup after loading the view, typically from a nib. self.view.backgroundcolor = [uicolor whitecolor]; if (!_picker || _picker == nil) { _picker = [[datepicker alloc] initwithframe:cgrectmake(0, 120, 375, 667)]; _picker.backgroundcolor = [uicolor whitecolor]; _picker.delegate = self; [self.view addsubview:_picker]; _picker.hidden = yes; } [self creatcustombutton]; } - (void)creatcustombutton{ uibutton *button = [uibutton buttonwithtype:uibuttontypecustom]; button.frame = cgrectmake(120, 20, 100, 40); [button settitle:@"日期选择器" forstate:uicontrolstatenormal]; [button settitlecolor:[uicolor redcolor] forstate:uicontrolstatenormal]; [button addtarget:self action:@selector(buttonaction:) forcontrolevents:uicontroleventtouchupinside ]; [self.view addsubview:button]; } - (void)buttonaction:(uibutton *)sender { if (!_picker || _picker == nil) { _picker = [[datepicker alloc] initwithframe:cgrectmake(0, 120, 375, 667)]; _picker.backgroundcolor = [uicolor whitecolor]; _picker.delegate = self; [self.view addsubview:_picker]; }else{ _picker.hidden = no; } } -(void)datepickerdelegateenteractionwithdatapicker:(datepicker *)picker{ nslog(@"======>%@",picker.date); nsstring *datestr = [nsstring stringwithformat:@"%@",picker.date]; [_picker removefromsuperview]; _picker = nil; [[[uialertview alloc]initwithtitle:@"提示" message:datestr delegate:self cancelbuttontitle:nil otherbuttontitles:@"确定", nil] show]; } - (void)didreceivememorywarning { [super didreceivememorywarning]; // dispose of any resources that can be recreated. } @end</pre><br> <pre></pre> <br> datepicker.h<br> <p><span style="font-size:14px"></span></p> <pre code_snippet_id="2093925" snippet_file_name="blog_20170103_2_3524896" name="code" class="objc">#import <uikit/uikit.h> @protocol datepickerdelegate; @interface datepicker : uiview <uipickerviewdatasource,uipickerviewdelegate> // 按照规范, 请把这些设置为外部不可见的 // 不可见的部分, 请放到.m文件里 @property (nonatomic, retain) uipickerview* yearpicker; // 年 @property (nonatomic, retain) uipickerview* monthpicker; // 月 @property (nonatomic, retain) uipickerview* daypicker; // 日 @property (nonatomic, retain) uipickerview* hourpicker; // 时 @property (nonatomic, retain) uipickerview* minutepicker; // 分 // 对外可见的 @property (nonatomic, retain) nsdate* date; // 当前date // 不可见的 @property (nonatomic, retain) uitoolbar* toolbar; // 工具条 @property (nonatomic, retain) uilabel* hintslabel; // 提示信息 // 不可见的 @property (nonatomic, retain) nsmutablearray* yeararray; @property (nonatomic, retain) nsmutablearray* montharray; @property (nonatomic, retain) nsmutablearray* dayarray; @property (nonatomic, retain) nsmutablearray* hourarray; @property (nonatomic, retain) nsmutablearray* minutearray; // 不可见的 @property (nonatomic, assign) nsuinteger yearvalue; @property (nonatomic, assign) nsuinteger monthvalue; @property (nonatomic, assign) nsuinteger dayvalue; @property (nonatomic, assign) nsuinteger hourvalue; @property (nonatomic, assign) nsuinteger minutevalue; @property (nonatomic, copy) nsstring *datestring; /** * 设置默认值为当前时间 */ -(void)resetdatetocurrentdate; /** * 设置提示信息 */ -(void)sethintstext:(nsstring*)hints; /** * 点击确定按钮 // 按照习惯,这个可木有 */ -(ibaction)actionenter:(id)sender; @property (nonatomic, assign) id<datepickerdelegate>delegate; @end @protocol datepickerdelegate <nsobject> /** * 点击确定后的事件 */ @optional -(void)datepickerdelegateenteractionwithdatapicker:(datepicker*)picker; @end </pre><br> <p></p> <p class="p1">datepicker.m<span class="s1"></span></p> <p class="p1"></p> <pre code_snippet_id="2093925" snippet_file_name="blog_20170103_3_4070113" name="code" class="objc"><pre code_snippet_id="2093925" snippet_file_name="blog_20170103_3_4070113" name="code" class="objc">#import "datepicker.h" #import "nsdate+calendar.h" #define mainheight [uiscreen mainscreen].bounds.size.height #define mainwidth [uiscreen mainscreen].bounds.size.width typedef enum { epickerviewtagyear = 2012, epickerviewtagmonth, epickerviewtagday, epickerviewtaghour, epickerviewtagminute }pickviewtag; @interface datepicker (private) /** * 创建数据源 */ -(void)createdatasource; /** * create month arrays */ -(void)createmontharraywithyear:(nsinteger)yearint month:(nsinteger)monthint; @end @implementation datepicker @synthesize delegate; @synthesize yearpicker, monthpicker, daypicker, hourpicker, minutepicker; @synthesize date; @synthesize yeararray, montharray, dayarray, hourarray, minutearray; @synthesize toolbar, hintslabel; @synthesize yearvalue, monthvalue; @synthesize dayvalue, hourvalue, minutevalue; #pragma mark - #pragma mark - - (id)initwithframe:(cgrect)frame { self = [super initwithframe:cgrectmake(0, mainheight - 260, mainwidth, 260)]; if (self) { // initialization code [self setbackgroundcolor:[uicolor blackcolor]]; nsmutablearray* temparray1 = [[nsmutablearray alloc] initwithcapacity:0]; nsmutablearray* temparray2 = [[nsmutablearray alloc] initwithcapacity:0]; nsmutablearray* temparray3 = [[nsmutablearray alloc] initwithcapacity:0]; nsmutablearray* temparray4 = [[nsmutablearray alloc] initwithcapacity:0]; nsmutablearray* temparray5 = [[nsmutablearray alloc] initwithcapacity:0]; [self setyeararray:temparray1]; [self setmontharray:temparray2]; [self setdayarray:temparray3]; [self sethourarray:temparray4]; [self setminutearray:temparray5]; // 更新数据源 [self createdatasource]; cgfloat prate = mainwidth/320; // 创建 toolbar & hintslabel & enter button uitoolbar* temptoolbar = [[uitoolbar alloc] initwithframe:cgrectmake(0, 0, mainwidth, 44)]; [self settoolbar:temptoolbar]; [self addsubview:self.toolbar]; // [toolbar settintcolor:[uicolor lighttextcolor]]; uilabel* temphintslabel = [[uilabel alloc] initwithframe:cgrectmake(5, 5, 250, 34)]; [self sethintslabel:temphintslabel]; [self.hintslabel setbackgroundcolor:[uicolor clearcolor]]; [self addsubview:self.hintslabel]; [self.hintslabel setfont:[uifont systemfontofsize:24.0f]]; [self.hintslabel settextcolor:[uicolor whitecolor]]; uibutton* tempbtn = [uibutton buttonwithtype:uibuttontypecustom]; // [tempbtn setbackgroundimage:[uiimage imagenamed:@"resourse.bundle/btnnormal.png"] forstate:uicontrolstatenormal]; // [tempbtn setbackgroundimage:[uiimage imagenamed:@"resourse.bundle/btnpressed.png"] forstate:uicontrolstatenormal]; [tempbtn settitle:@"确定" forstate:uicontrolstatenormal]; [tempbtn sizetofit]; [tempbtn settitlecolor:[uicolor darktextcolor] forstate:uicontrolstatenormal]; [tempbtn setcenter:cgpointmake(mainwidth-15-tempbtn.frame.size.width*.5, 22)]; [tempbtn addtarget:self action:@selector(actionenter:) forcontrolevents:uicontroleventtouchupinside]; [self addsubview:tempbtn]; // 初始化各个视图 uipickerview* yearpickertemp = [[uipickerview alloc] initwithframe:cgrectmake(0, 44, 80, 216)]; [self setyearpicker:yearpickertemp]; [self.yearpicker setframe:cgrectmake(0*prate, 44, 80*prate, 216)]; // uilabel *label = [[uilabel alloc] initwithframe:cgrectmake( 75*prate, 141 ,20, 20)]; // label.font = [uifont systemfontofsize:18]; // label.text = @"年"; // [self addsubview:label]; uipickerview* monthpickertemp = [[uipickerview alloc] initwithframe:cgrectmake(80, 44, 56*prate, 216)]; [self setmonthpicker:monthpickertemp]; [self.monthpicker setframe:cgrectmake(80*prate, 44, 56*prate, 216)]; uipickerview* daypickertemp = [[uipickerview alloc] initwithframe:cgrectmake(141, 44, 60, 216)]; [self setdaypicker:daypickertemp]; [self.daypicker setframe:cgrectmake(126*prate, 44, 60*prate, 216)]; uipickerview* hourpickertemp = [[uipickerview alloc] initwithframe:cgrectmake(201, 44, 60, 216)]; [self sethourpicker:hourpickertemp]; [self.hourpicker setframe:cgrectmake(186*prate, 44, 60*prate, 216)]; uipickerview* minutespickertemp = [[uipickerview alloc] initwithframe:cgrectmake(261, 44, 60, 216)]; [self setminutepicker:minutespickertemp]; [self.minutepicker setframe:cgrectmake(246*prate, 44, 60*prate, 216)]; nsarray *arrar = @[@"年",@"月",@"日",@"时",@"分"]; uilabel *namelabel; for (int i = 0; i < 5; i++) { switch (i) { case 0: { namelabel = [[uilabel alloc] initwithframe:cgrectmake( 75*prate, 141 ,20, 20)]; break; } case 1: { namelabel = [[uilabel alloc] initwithframe:cgrectmake( 126*prate, 141 ,20, 20)]; break; } case 2: { namelabel = [[uilabel alloc] initwithframe:cgrectmake( 186*prate, 141 ,20, 20)]; break; } case 3: { namelabel = [[uilabel alloc] initwithframe:cgrectmake( 246*prate, 141 ,20, 20)]; break; } case 4: { namelabel = [[uilabel alloc] initwithframe:cgrectmake( 296*prate, 141 ,20, 20)]; break; } default: break; } namelabel.font = [uifont systemfontofsize:18]; namelabel.text = [nsstring stringwithformat:@"%@",arrar[i]]; [self addsubview:namelabel]; } [self.yearpicker setdatasource:self]; [self.monthpicker setdatasource:self]; [self.daypicker setdatasource:self]; [self.hourpicker setdatasource:self]; [self.minutepicker setdatasource:self]; [self.yearpicker setdelegate:self]; [self.monthpicker setdelegate:self]; [self.daypicker setdelegate:self]; [self.hourpicker setdelegate:self]; [self.minutepicker setdelegate:self]; [self.yearpicker settag:epickerviewtagyear]; [self.monthpicker settag:epickerviewtagmonth]; [self.daypicker settag:epickerviewtagday]; [self.hourpicker settag:epickerviewtaghour]; [self.minutepicker settag:epickerviewtagminute]; [self addsubview:self.yearpicker]; [self addsubview:self.monthpicker]; [self addsubview:self.daypicker]; [self addsubview:self.hourpicker]; [self addsubview:self.minutepicker]; [self.yearpicker setshowsselectionindicator:yes]; [self.monthpicker setshowsselectionindicator:yes]; [self.daypicker setshowsselectionindicator:yes]; [self.hourpicker setshowsselectionindicator:yes]; [self.minutepicker setshowsselectionindicator:yes]; [self resetdatetocurrentdate]; } return self; } #pragma mark - uipickerviewdatasource - (nsinteger)numberofcomponentsinpickerview:(uipickerview *)pickerview{ return 1; } //- (cgfloat)pickerview:(uipickerview *)pickerview widthforcomponent:(nsinteger)component{ // if (epickerviewtagyear == pickerview.tag) { // return 60.0f; // } else { // return 40.0f; // } //} -(nsinteger)pickerview:(uipickerview *)pickerview numberofrowsincomponent:(nsinteger)component{ if (epickerviewtagyear == pickerview.tag) { return [self.yeararray count]; } if (epickerviewtagmonth == pickerview.tag) { return [self.montharray count]; } if (epickerviewtagday == pickerview.tag) { return [self.dayarray count]; } if (epickerviewtaghour == pickerview.tag) { return [self.hourarray count]; } if (epickerviewtagminute == pickerview.tag) { return [self.minutearray count]; } return 0; } #pragma makr - uipickerviewdelegate - (nsstring *)pickerview:(uipickerview *)pickerview titleforrow:(nsinteger)row forcomponent:(nsinteger)component{ if (epickerviewtagyear == pickerview.tag) { return [self.yeararray objectatindex:row]; } if (epickerviewtagmonth == pickerview.tag) { return [self.montharray objectatindex:row]; } if (epickerviewtagday == pickerview.tag) { return [self.dayarray objectatindex:row]; } if (epickerviewtaghour == pickerview.tag) { return [self.hourarray objectatindex:row]; } if (epickerviewtagminute == pickerview.tag) { return [self.minutearray objectatindex:row]; } return @""; } - (void)pickerview:(uipickerview *)pickerview didselectrow:(nsinteger)row incomponent:(nsinteger)component{ if (epickerviewtagyear == pickerview.tag) { self.yearvalue = [[self.yeararray objectatindex:row] intvalue]; } else if(epickerviewtagmonth == pickerview.tag){ self.monthvalue = [[self.montharray objectatindex:row] intvalue]; } else if(epickerviewtagday == pickerview.tag){ self.dayvalue = [[self.dayarray objectatindex:row]intvalue]; } else if(epickerviewtaghour == pickerview.tag){ self.hourvalue = [[self.hourarray objectatindex:row]intvalue]; } else if(epickerviewtagminute == pickerview.tag){ self.minutevalue = [[self.minutearray objectatindex:row] intvalue]; } if (epickerviewtagmonth == pickerview.tag || epickerviewtagyear == pickerview.tag) { [self createmontharraywithyear:self.yearvalue month:self.monthvalue]; [self.daypicker reloadallcomponents]; } nsstring* str = [nsstring stringwithformat:@"%04d%02d%02lu%02lu%02lu",self.yearvalue, self.monthvalue, (unsigned long)self.dayvalue, (unsigned long)self.hourvalue, (unsigned long)self.minutevalue]; [self setdate:[self datefromstring:str withformat:@"yyyymmddhhmm"]]; } #pragma mark - 年月日闰年=情况分析 /** * 创建数据源 */ -(void)createdatasource{ // 年 nsinteger yearint = [[nsdate date] getyear]; [self.yeararray removeallobjects]; for (int i=yearint ; i<= yearint + 10; i++) { [self.yeararray addobject:[nsstring stringwithformat:@"%d",i]]; } // 月 [self.montharray removeallobjects]; for (int i=1; i<=12; i++) { [self.montharray addobject:[nsstring stringwithformat:@"%d",i]]; } nsinteger month = [[nsdate date] getmonth]; [self createmontharraywithyear:yearint month:month]; // 时 [self.hourarray removeallobjects]; for(int i=0; i<24; i++){ [self.hourarray addobject:[nsstring stringwithformat:@"%02d",i]]; } // 分 [self.minutearray removeallobjects]; for(int i=0; i<60; i++){ [self.minutearray addobject:[nsstring stringwithformat:@"%02d",i]]; } } #pragma mark - -(void)resetdatetocurrentdate{ nsdate* nowdate = [nsdate date]; [self.yearpicker selectrow:0 incomponent:0 animated:yes]; [self.monthpicker selectrow:[nowdate getmonth]-1 incomponent:0 animated:yes]; [self.daypicker selectrow:[nowdate getday]-1 incomponent:0 animated:yes]; [self.hourpicker selectrow:[nowdate gethour] incomponent:0 animated:yes]; [self.minutepicker selectrow:[nowdate getminute] incomponent:0 animated:yes]; [self setyearvalue:[nowdate getyear]]; [self setmonthvalue:[nowdate getmonth]]; [self setdayvalue:[nowdate getday]]; [self sethourvalue:[nowdate gethour]]; [self setminutevalue:[nowdate getminute]]; nsstring* str = [nsstring stringwithformat:@"%04d%02d%02d%02d%02d",self.yearvalue, self.monthvalue, self.dayvalue, self.hourvalue, self.minutevalue]; [self setdate:[self datefromstring:str withformat:@"yyyymmddhhmm"]]; self.datestring = [self datestring:self.date]; } #pragma mark - -(void)createmontharraywithyear:(nsinteger)yearint month:(nsinteger)monthint{ int enddate = 0; switch (monthint) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: enddate = 31; break; case 4: case 6: case 9: case 11: enddate = 30; break; case 2: // 是否为闰年 if (yearint % 400 == 0) { enddate = 29; } else { if (yearint % 100 != 0 && yearint %4 ==4) { enddate = 29; } else { enddate = 28; } } break; default: break; } if (self.dayvalue > enddate) { self.dayvalue = enddate; } // 日 [self.dayarray removeallobjects]; for(int i=1; i<=enddate; i++){ [self.dayarray addobject:[nsstring stringwithformat:@"%d",i]]; } } #pragma mark - 点击确定按钮 -(void)actionenter:(id)sender{ if (self.date == nil) { self.date =[nsdate date]; } nslog(@"====>%@",self.date); if (self.delegate && [self.delegate respondstoselector:@selector(datepickerdelegateenteractionwithdatapicker:)]) { [self.delegate datepickerdelegateenteractionwithdatapicker:self]; } [self removefromsuperview]; } #pragma mark - 设置提示信息 -(void)sethintstext:(nsstring*)hints{ [self.hintslabel settext:hints]; } #pragma mark - -(void)removefromsuperview{ self.delegate = nil; [super removefromsuperview]; } - (nsdate *)datefromstring:(nsstring *)str withformat:(nsstring *)format{ nsdateformatter *dateformatter = [[nsdateformatter alloc] init]; [dateformatter settimezone:[nstimezone timezonewithabbreviation:@"utc"]]; [dateformatter setdateformat:format]; nsdate* datefromstring = [dateformatter datefromstring:str]; return datefromstring; } - (nsstring *)datestring:(nsdate *)date{ nsdateformatter *dateformatter = [[nsdateformatter alloc] init]; [dateformatter settimezone:[nstimezone timezonewithabbreviation:@"utc"]]; [dateformatter setdateformat:@"yyyyy-mm-dd hh:mm:ss"]; nsstring *datestring = [dateformatter stringfromdate:date]; return datestring; } @end </pre><br> <pre></pre> <br> nsdate+calendar.h<br> <p></p> <p class="p1"></p> <pre code_snippet_id="2093925" snippet_file_name="blog_20170103_4_4657975" name="code" class="objc">#import <foundation/foundation.h> //头文件部分 @interface nsdate (calendar) /** *获取当前月的天数 */ - (nsuinteger)yhbasenumberofdaysincurrentmonth; /** *获取本月第一天 */ - (nsdate *)yhbasefirstdayofcurrentmonth; //下面这些方法用于获取各种整形的数据 /** *确定某天是周几 */ -(int)yhbaseweekly; /** *年月日 时分秒 */ -(int)getyear; -(int)getmonth; -(int)getday; -(int)gethour; -(int)getminute; -(int)getsecond; @end </pre> <p></p> <p class="p1"><br> </p> <p class="p1"><br> </p> nsdate+calendar.m <p class="p1"></p> <pre code_snippet_id="2093925" snippet_file_name="blog_20170103_5_503109" name="code" class="objc">#import "nsdate+calendar.h" @implementation nsdate (calendar) -(nsuinteger)yhbasenumberofdaysincurrentmonth{ return [[nscalendar currentcalendar] rangeofunit:nsdaycalendarunit inunit:nsmonthcalendarunit fordate:self].length; } - (nsdate *)yhbasefirstdayofcurrentmonth { nsdate *startdate = nil; bool ok = [[nscalendar currentcalendar] rangeofunit:nsmonthcalendarunit startdate:&startdate interval:null fordate:self]; nsassert1(ok, @"failed to calculate the first day of the month based on %@", self); return startdate; } -(int)yhbaseweekly{ return (int)[[nscalendar currentcalendar] ordinalityofunit:nsdaycalendarunit inunit:nsweekcalendarunit fordate:self]; } -(int)getyear{ nscalendar *calendar = [nscalendar currentcalendar]; nsuinteger unitflags = nsyearcalendarunit | nsmonthcalendarunit | nsdaycalendarunit | nshourcalendarunit | nsminutecalendarunit | nssecondcalendarunit; nsdatecomponents *datecomponent = [calendar components:unitflags fromdate:self]; return (int)datecomponent.year; } -(int)getmonth{ nscalendar *calendar = [nscalendar currentcalendar]; nsuinteger unitflags = nsyearcalendarunit | nsmonthcalendarunit | nsdaycalendarunit | nshourcalendarunit | nsminutecalendarunit | nssecondcalendarunit; nsdatecomponents *datecomponent = [calendar components:unitflags fromdate:self]; return (int)datecomponent.month; } -(int)getday{ nscalendar *calendar = [nscalendar currentcalendar]; nsuinteger unitflags = nsyearcalendarunit | nsmonthcalendarunit | nsdaycalendarunit | nshourcalendarunit | nsminutecalendarunit | nssecondcalendarunit; nsdatecomponents *datecomponent = [calendar components:unitflags fromdate:self]; return (int)datecomponent.day; } -(int)gethour{ nscalendar *calendar = [nscalendar currentcalendar]; nsuinteger unitflags = nsyearcalendarunit | nsmonthcalendarunit | nsdaycalendarunit | nshourcalendarunit | nsminutecalendarunit | nssecondcalendarunit; nsdatecomponents *datecomponent = [calendar components:unitflags fromdate:self]; return (int)datecomponent.hour; } -(int)getminute{ nscalendar *calendar = [nscalendar currentcalendar]; nsuinteger unitflags = nsyearcalendarunit | nsmonthcalendarunit | nsdaycalendarunit | nshourcalendarunit | nsminutecalendarunit | nssecondcalendarunit; nsdatecomponents *datecomponent = [calendar components:unitflags fromdate:self]; return (int)datecomponent.minute; } -(int)getsecond{ nscalendar *calendar = [nscalendar currentcalendar]; nsuinteger unitflags = nsyearcalendarunit | nsmonthcalendarunit | nsdaycalendarunit | nshourcalendarunit | nsminutecalendarunit | nssecondcalendarunit; nsdatecomponents *datecomponent = [calendar components:unitflags fromdate:self]; return (int)datecomponent.second; } @end </pre><br> <br> <br> <p></p> </pre>
以上这篇ios自定义uidatepicker日期选择器视图分享就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。