41
35

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 5 years have passed since last update.

UITextfieldとUIDatePickerを連携させる

Last updated at Posted at 2016-01-27

こんな感じでUITextfieldを選択すると、UIDatePickerが立ち上がって
日付を入力させる方法についてのご紹介です。
コードで比較的ラクに実装できます。
Screen Shot 2016-01-27 at 14.48.50.png

#UITextfieldを準備
まずはUITextfieldをstoryboardのuivewcontroller上に配置。
Outletで接続しておきます。

#コード編集

code
class birthdayInputViewController: UIViewController {
    
    @IBOutlet weak var birthday: UITextField!
    var toolBar:UIToolbar!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //datepicker上のtoolbarのdoneボタン
        toolBar = UIToolbar()
        toolBar.sizeToFit()
        let toolBarBtn = UIBarButtonItem(title: "DONE", style: .Plain, target: self, action: "doneBtn")
        toolBar.items = [toolBarBtn]
        birthday.inputAccessoryView = toolBar
    }
    
    //テキストフィールドが選択されたらdatepickerを表示
    @IBAction func textFieldEditing(sender: UITextField) {
        let datePickerView:UIDatePicker = UIDatePicker()
        datePickerView.datePickerMode = UIDatePickerMode.Date
        sender.inputView = datePickerView
        datePickerView.addTarget(self, action: Selector("datePickerValueChanged:"), forControlEvents: UIControlEvents.ValueChanged)
    }
    
    //datepickerが選択されたらtextfieldに表示
    func datePickerValueChanged(sender:UIDatePicker) {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat  = "yyyy/MM/dd";
        birthday.text = dateFormatter.stringFromDate(sender.date)
    }
    
    //toolbarのdoneボタン
    func doneBtn(){
        birthday.resignFirstResponder()
    }
}

これだけで実装完了です。

41
35
1

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
41
35

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?