UIDatepickerはなんでキーボードみたいに下から出たり引っ込んだりしてくれないんでしょうね。
で調べたらこちらの方が書かれていました。
テキストフィールドをタップして、キーボードの代わりにpickerViewやdatePickerを出す – デビューが遅すぎたびび子ママのプログラム奮闘記
上記を参考にちょっといじりました。
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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
#import "ViewController.h" @interface ViewController ()<UITextFieldDelegate> @property (weak, nonatomic) IBOutlet UITextField *testText; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. //デートピッカーのインスタンス作成初期化 UIDatePicker *datePicker= [[UIDatePicker alloc]init]; //デートピッカーのモードを設定 datePicker.datePickerMode = UIDatePickerModeDate; //テキストフィールドの入力をデートピッカーに変更 _testText.inputView = datePicker; //ピッカーの値が変更された時に呼ばれるメソッドを設定 [datePicker addTarget:self action:@selector(datePicker_ValueChanged:) forControlEvents:UIControlEventValueChanged]; //テキスト入力のキーボードに閉じるボタンを付ける UIView* accessoryView =[[UIView alloc] initWithFrame:CGRectMake(0,0,self.view.frame.size.width,40)]; accessoryView.backgroundColor = [UIColor lightGrayColor]; // ボタンを作成する。 UIButton* closeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; closeButton.frame = CGRectMake(self.view.frame.size.width-100,10,100,20); [closeButton setTitle:@"閉じる" forState:UIControlStateNormal]; // ボタンを押したときによばれる動作を設定する。 [closeButton addTarget:self action:@selector(closeKeyboard:) forControlEvents:UIControlEventTouchUpInside]; // ボタンをViewに貼る [accessoryView addSubview:closeButton]; //ボタンを適用するテキストフィールドに設定 _testText.inputAccessoryView = accessoryView; } //キーボードを閉じる -(void)closeKeyboard:(id)sender { [self.testText resignFirstResponder]; } //ピッカーの値を反映 - (void)datePicker_ValueChanged:(id)sender { UIDatePicker *datePicker = sender; // 日付の表示形式を設定 NSDateFormatter *df = [[NSDateFormatter alloc]init]; df.dateFormat = @"yyyy/MM/dd HH:mm"; self.testText.text = [NSString stringWithFormat:@"%@", [df stringFromDate:datePicker.date]]; NSLog(@"%@", [df stringFromDate:datePicker.date]); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end |