UIDatePickerを下からにゅっと出す。

UIDatepickerはなんでキーボードみたいに下から出たり引っ込んだりしてくれないんでしょうね。

で調べたらこちらの方が書かれていました。
テキストフィールドをタップして、キーボードの代わりにpickerViewやdatePickerを出す – デビューが遅すぎたびび子ママのプログラム奮闘記

上記を参考にちょっといじりました。

#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

iOS Simulator Screen Shot 2015.10.10 19.15.46
むつかしーい…。

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です