0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

UITextFieldのキーボードにUIDatePickerを設定する

Last updated at Posted at 2022-04-23

はじめに

プロフィールの誕生日欄(textField)を入力する際に、キーボードをUIDatePickerにしようと思ったので記事にしてみました。

環境

・Swift 5.5.2
・Xcode 13.3.1

使ってみる

再利用できるようにクラスにしてみました。

DatePicker.swift
final class DatePicker {

    static let picker = UIDatePicker()
    static let formatter = DateFormatter()

    static func setup(_ vc: UIViewController, action: Selector, for textField: UITextField) {
        picker.datePickerMode = .date
        picker.preferredDatePickerStyle = .wheels
        picker.locale = Locale(identifier: "ja_JP")
        picker.addTarget(vc, action: action, for: .valueChanged)
        formatter.dateFormat  = "yyyy/MM/dd"
        textField.inputView = picker
    }
}

Controller側

ViewController.swift
override func viewDidLoad() {
    super.viewDidLoad()
    DatePicker.setup(self, action: #selector(datePickerValueChanged), for: dateTextField)
}

@objc private func datePickerValueChanged(sender: UIDatePicker) {
     dateTextField.text = DatePicker.formatter.string(from: sender.date)
}

これでdatePickerの値を変更するたびにtextFieldのテキストも変更されていきます。
datePickerのスタイルや、フォーマット等はお好みで変更してください。

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?