下図のように編集開始時にDatePicker
を起動させ,時間変更時に変更時間をTextFieldに反映させます.
まずTextFieldのDelegateを追加します.
ViewController.swift
class ViewController: UIViewController, UITextFieldDelegate
次に以下のコードを追加hします
ViewController.swift
var toolBar:UIToolbar!
@IBOutlet var wakeTimeTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
wakeTimeTextField.delegate = self
setupToolbar()
}
func setupToolbar() {
//datepicker上のtoolbarのdoneボタン
toolBar = UIToolbar()
toolBar.sizeToFit()
let toolBarBtn = UIBarButtonItem(title: "DONE", style: .plain, target: self, action: #selector(doneBtn))
toolBar.items = [toolBarBtn]
wakeTimeTextField.inputAccessoryView = toolBar
}
func textFieldDidBeginEditing(_ textField: UITextField) {
let datePickerView:UIDatePicker = UIDatePicker()
datePickerView.datePickerMode = UIDatePicker.Mode.time
textField.inputView = datePickerView
datePickerView.addTarget(self, action: #selector(datePickerValueChanged(sender:)), for: UIControl.Event.valueChanged)
}
//datepickerが選択されたらtextfieldに表示
@objc func datePickerValueChanged(sender:UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "H:mm";
wakeTimeTextField.text = dateFormatter.string(from: sender.date)
}
//toolbarのdoneボタン
@objc func doneBtn(){
wakeTimeTextField.resignFirstResponder()
}