點(diǎn)擊textfield實(shí)現(xiàn)彈出UIDatePicker日期選擇器

對(duì)于實(shí)現(xiàn)點(diǎn)擊TextField彈出日期選擇器的方法有多種多樣,可以將UIDatePicker作為textfield的inputView,或者用通知中心監(jiān)聽鍵盤彈出的響應(yīng)事件,也可通過textfield的代理方法來實(shí)現(xiàn)。

這里我選擇用textfield的inputView來實(shí)現(xiàn)該操作。(只做簡單的講解,其實(shí)還可通過把toolbar設(shè)置為inputAccessoryView實(shí)現(xiàn)拓展功能)

首先在控制器的.h文件聲明三個(gè)成員變量

UIDatePicker*datePicker;

UITextField*dateTextField;

NSLocale*datelocale;

然后初始化一個(gè)UITextfield實(shí)例對(duì)象,這里不做說明了(太Easy了好么)。

再對(duì).h中聲明的datePicker實(shí)例化

datePicker= [[UIDatePickeralloc]init];

datelocale= [[NSLocalealloc]initWithLocaleIdentifier:@"zh_zn"];//設(shè)置時(shí)區(qū)

datePicker.locale=datelocale;

datePicker.timeZone= [NSTimeZonetimeZoneWithName:@"GMT"];

datePicker.datePickerMode=UIDatePickerModeDate;

//這句是重點(diǎn)

dateTextField.inputView=datePicker;

蘋果使用的是格里高利歷 這里進(jìn)行設(shè)置

NSDate*localDate = [NSDatedate];

NSCalendar*calendar = [[NSCalendaralloc]initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents*components = [[NSDateComponentsalloc]init];

[componentssetYear:-100];

[componentssetMonth:12];

[componentssetDay:30];

NSDate*minDate = [calendardateByAddingComponents:componentstoDate:localDateoptions:0];

_datePicker.maximumDate= localDate;

_datePicker.minimumDate= minDate;

上面利用日期偏移設(shè)置最大日期和最小日期

//接下來為日期選擇器添加事件 條件是當(dāng)值改變 使顯示在textfield上的時(shí)間做出改變

[_datePickeraddTarget:self action:@selector(selectDate:)forControlEvents:UIControlEventValueChanged];

//事件中設(shè)置日期顯示格式和顯示位置

-(void)selectDate:(UIDatePicker *)datePicker

{

?NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];

dateFormatter setDateFormat = @"yyyy-MM-dd";

[dateFormatter setLocale:dateLocale];

self.dateTextField.text = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:datePicker.date]];

}

以上就可以實(shí)現(xiàn)了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容