3
3

More than 3 years have passed since last update.

TextFieldをタップしたら日付のピッカーが出て欲しい

Posted at

テキストフィールドに年月日を入力したかった

テキストフィールドをタップすると普通はキーボードが出ますよね?
しかし今回はドラムロールというピッカーというか、そういうのが出て欲しかったんです。
ポンコツな私でも使える方法が合ったのでメモがてらここに書きます。

ポイントは
・日付を出すピッカーである「DatePicker」ってものが存在した

ViewController.swift
@IBOutlet weak var Appreciation: UITextField!

    let datePicker = UIDatePicker()

    override func viewDidLoad() {
        super.viewDidLoad()

        createDatePicker()
    }

   func createDatePicker(){

        // DatePickerModeをDate(日付)に設定
        datePicker.datePickerMode = .date

        // DatePickerを日本語化
        datePicker.locale = NSLocale(localeIdentifier: "ja_JP") as Locale

        // textFieldのinputViewにdatepickerを設定
        Appreciation.inputView = datePicker

        // UIToolbarを設定
        let toolbar = UIToolbar()
        toolbar.sizeToFit()

        // Doneボタンを設定(押下時doneClickedが起動)
        let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(doneClicked))

        // Doneボタンを追加
        toolbar.setItems([doneButton], animated: true)

        // FieldにToolbarを追加
        Appreciation.inputAccessoryView = toolbar
    }

    @objc func doneClicked(){
        let dateFormatter = DateFormatter()

        // 持ってくるデータのフォーマットを設定
        dateFormatter.dateStyle = .medium
        dateFormatter.timeStyle = .none
        dateFormatter.locale    = NSLocale(localeIdentifier: "ja_JP") as Locale!
        dateFormatter.dateStyle = DateFormatter.Style.medium

        // textFieldに選択した日付を代入
        Appreciation.text = dateFormatter.string(from: datePicker.date

        // キーボードを閉じる
        self.view.endEditing(true)
    }

新しいXcodeだとある程度エラーが出ますが、そこはFixで直しちゃいましょう!

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3