[iOS Dev] 點擊UITextField 跳出UIDatePicker以選取日期(生日,NSDate)
這篇文章講的功能 不會自動幫忙移動畫面以顯示原本的 UITextField
所以當 UIDatePicker 跳出來的時候 是有可能擋住 UITextField
我想應該是有辦法加 但我目前還沒仔細研究
首先在 ViewController.h 加上 delegate
|
1
2
3
4
5
6
7
8
|
// 加上 UITextFieldDelegate@interface ViewController : UIViewController <UITextFieldDelegate> {// 例子需要的變數 UIDatePicker *datePicker; UITextField *dateTextField; NSLocale *datelocale;}@end |
接著以下是 ViewController.m 要加的 method
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
- (void)viewDidLoad{ [super viewDidLoad];// 建立 UITextField dateTextField = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, 120, 40)];// 以下兩行是測試用 可以依照自己的需求增減屬性 dateTextField.text = @"test"; dateTextField.backgroundColor = [UIColor blueColor];// 記得要設定 delegate dateTextField.delegate = self;// 加入 view 中 [self.view addSubview:dateTextField];// 建立 UIDatePicker datePicker = [[UIDatePicker alloc]init];// 時區的問題請再找其他協助 不是本篇重點 datelocale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_TW"]; datePicker.locale = datelocale; datePicker.timeZone = [NSTimeZone timeZoneWithName:@"GMT"]; datePicker.datePickerMode = UIDatePickerModeDate;// 以下這行是重點 (螢光筆畫兩行) 將 UITextField 的 inputView 設定成 UIDatePicker // 則原本會跳出鍵盤的地方 就改成選日期了 dateTextField.inputView = datePicker;// 建立 UIToolbar UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];// 選取日期完成鈕 並給他一個 selector UIBarButtonItem *right = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(cancelPicker)];// 把按鈕加進 UIToolbar toolBar.items = [NSArray arrayWithObject:right];// 以下這行也是重點 (螢光筆畫兩行) // 原本應該是鍵盤上方附帶內容的區塊 改成一個 UIToolbar 並加上完成鈕 dateTextField.inputAccessoryView = toolBar; }// 按下完成鈕後的 method-(void) cancelPicker {// endEditing: 是結束編輯狀態的 method if ([self.view endEditing:NO]) {// 以下幾行是測試用 可以依照自己的需求增減屬性 NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; NSString *dateFormat = [NSDateFormatter dateFormatFromTemplate:@"yyyy-MM-dd" options:0 locale:datelocale]; [formatter setDateFormat:dateFormat]; [formatter setLocale:datelocale]; // 將選取後的日期 填入 UITextField dateTextField.text = [NSString stringWithFormat:@"%@",[formatter stringFromDate:datePicker.date]]; }} |
這樣基本上應該就可以動了
沒有使用 ARC 的話 記得要把該 release 的 release 掉
浙公网安备 33010602011771号