Help us understand the problem. What is going on with this article?

Swiftで UITextField から UIDatePicker を呼び出して Toolbarに完了ボタンなどを用意する

More than 3 years have passed since last update.

UITextField をタップした時にUIDatePickerを呼び出して、日付を入力する方法です。
どうせなら、日付選んだら「完了」ボタンを押して UIDatePicker を消すのと、「今日」ボタンを押したら、今日の日付を UITextField に設定する機能を用意してみました。

UITextField は StoryBoardでもいい

UITextField をStoryBoardに配置しているのを使います(コードから生成しても構いません)。

プレビュー画面

preview.gif

inputView

inputView で、ソフトウェアキーボードとUIDatePickerを入れ替えています

inputAccessoryView

inputAccessoryView にUIToolbarを入れて表示しています

日付の選択とか

addTarget で設定しています。

ソース

import UIKit

class ViewController: UIViewController, UIToolbarDelegate {

    @IBOutlet weak var textField: UITextField!
    //var textField: UITextField!
    var toolBar:UIToolbar!
    var myDatePicker: UIDatePicker!

    override func viewDidLoad() {
        super.viewDidLoad()

        // 入力欄の設定
        //textField = UITextField(frame: CGRectMake(self.view.frame.size.width/3, 100, 0, 0))
        textField.placeholder = dateToString(NSDate())
        textField.text        = dateToString(NSDate())
        //textField.sizeToFit()
        self.view.addSubview(textField)

        // UIDatePickerの設定
        myDatePicker = UIDatePicker()
        myDatePicker.addTarget(self, action: "changedDateEvent:", forControlEvents: UIControlEvents.ValueChanged)
        myDatePicker.datePickerMode = UIDatePickerMode.Date
        textField.inputView = myDatePicker

        // UIToolBarの設定
        toolBar = UIToolbar(frame: CGRectMake(0, self.view.frame.size.height/6, self.view.frame.size.width, 40.0))
        toolBar.layer.position = CGPoint(x: self.view.frame.size.width/2, y: self.view.frame.size.height-20.0)
        toolBar.barStyle = .BlackTranslucent
        toolBar.tintColor = UIColor.whiteColor()
        toolBar.backgroundColor = UIColor.blackColor()

        let toolBarBtn      = UIBarButtonItem(title: "完了", style: .Bordered, target: self, action: "tappedToolBarBtn:")
        let toolBarBtnToday = UIBarButtonItem(title: "今日", style: .Bordered, target: self, action: "tappedToolBarBtnToday:")

        toolBarBtn.tag = 1
        toolBar.items = [toolBarBtn, toolBarBtnToday]

        textField.inputAccessoryView = toolBar
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    // 「完了」を押すと閉じる
    func tappedToolBarBtn(sender: UIBarButtonItem) {
        textField.resignFirstResponder()
    }

    // 「今日」を押すと今日の日付をセットする
    func tappedToolBarBtnToday(sender: UIBarButtonItem) {
        myDatePicker.date = NSDate()
        changeLabelDate(NSDate())
    }

    //
    func changedDateEvent(sender:AnyObject?){
        var dateSelecter: UIDatePicker = sender as UIDatePicker
        self.changeLabelDate(myDatePicker.date)
    }

    func changeLabelDate(date:NSDate) {
        textField.text = self.dateToString(date)
    }

    func dateToString(date:NSDate) ->String {
        let calender: NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)
        let comps: NSDateComponents = calender.components(NSCalendarUnit.YearCalendarUnit|NSCalendarUnit.MonthCalendarUnit|NSCalendarUnit.DayCalendarUnit|NSCalendarUnit.HourCalendarUnit|NSCalendarUnit.MinuteCalendarUnit|NSCalendarUnit.SecondCalendarUnit|NSCalendarUnit.WeekdayCalendarUnit, fromDate: date)

        var date_formatter: NSDateFormatter = NSDateFormatter()
        var weekdays: Array  = [nil, "日", "月", "火", "水", "木", "金", "土"]

        date_formatter.locale     = NSLocale(localeIdentifier: "ja")
        date_formatter.dateFormat = "yyyy年MM月dd日(\(weekdays[comps.weekday])) "

        return date_formatter.stringFromDate(date)
    }
}


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
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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