Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
32
Help us understand the problem. What is going on with this article?
@iritec

UITextfieldとUIDatePickerを連携させる

More than 5 years have passed since last update.

こんな感じで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()
    }
}

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

32
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
iritec
プログラミングのメンターサービスMENTAをつくってます http://menta.work / 個人開発コミュニティ「入江開発室」を運営(約100名) / WEB制作会社→フリー→法人化→受託をやめてサービスに専念

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
32
Help us understand the problem. What is going on with this article?