天天看點

iOS學習之UIDatePicker控件使用

iOS上的選擇時間日期的控件是這樣的,左邊是時間和日期混合,右邊是單純的日期模式。

iOS學習之UIDatePicker控件使用

,  

iOS學習之UIDatePicker控件使用

您可以選擇自己需要的模式,Time, Date,Date and Time  , Count Down Timer四種模式。

iOS學習之UIDatePicker控件使用

本篇文章簡單介紹下PickerDate控件的使用

1、建立一個Singe View Application,命名為DatePickDemo,其他設定如圖

iOS學習之UIDatePicker控件使用

2、放置控件

打開ViewController.xib,拖拽一個DatePicker控件放到界面上,再拖拽一個Button控件放到界面上,輕按兩下Button,輸入"選擇日期時間"

iOS學習之UIDatePicker控件使用

3、建立xib和ViewController的關聯

按下command+alt+enter鍵打開Assistant Editor,選中DatePicker按住Control鍵,拖拽到viewController.h上,

iOS學習之UIDatePicker控件使用

建立Outlet datePicker。

以同樣方式給Button建立一個Action關聯映射,命名為selectDate,事件類型為預設的Touch Up Inside。

4、實作代碼

單擊ViewController.m,找到剛才建立的

- (IBAction)selectDate:(id)sender {

}

在這裡添加響應代碼

[cpp]  view plain copy

  1. - (IBAction)selectDate:(id)sender {  
  2.     NSDate *select = [datePicker date];  
  3.     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];  
  4.     [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];  
  5.     NSString *dateAndTime =  [dateFormatter stringFromDate:select];  
  6.     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"時間提示" message:dateAndTime delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];  
  7.     [alert show];  
  8. }  

運作看效果:

iOS學習之UIDatePicker控件使用

5、修改模式成Date模式,修改代碼

[cpp]  view plain copy

  1. [dateFormatter setDateFormat:@"yyyy-MM-dd"];  
iOS學習之UIDatePicker控件使用

例子代碼:https://github.com/schelling/YcDemo

著作權聲明:本文由http://blog.csdn.net/totogo2010/原創,歡迎轉載分享。請尊重作者勞動,轉載時保留該聲明和作者部落格連結,謝謝