iOS9 UIDatePicker Example with UIToolBar in Swift 3.0.

UIDatePicker object use to select the date and time, The UIDatePicker class have multiple rotate wheels and take value from that wheel and give one object of UIDatePicker and to get date from UIDatePicker object.

In this example, take one textFiled in which to open the datePicker using inputView. and adding toolbar in DatePicker.

Follow the below steps :

Step 1 :  Adding one textFiled named  textField_Date in ViewController and give IBOutlet connection and delegate. also take one UIDatePicker variable.
@IBOutlet weak var textField_Date: UITextField!
var datePicker : UIDatePicker!
Step 2 : The function pickUpDate to create UIDatePicker with ToolBar. 
func pickUpDate(_ textField : UITextField){

    // DatePicker
    self.datePicker = UIDatePicker(frame:CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 216))
    self.datePicker.backgroundColor = UIColor.white
    self.datePicker.datePickerMode =
    textField.inputView = self.datePicker

    // ToolBar
    let toolBar = UIToolbar()
    toolBar.barStyle = .default
    toolBar.isTranslucent = true
    toolBar.tintColor = UIColor(red: 92/255, green: 216/255, blue: 255/255, alpha: 1)

    // Adding Button ToolBar
    let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(ViewController.doneClick))
    let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
    let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(ViewController.cancelClick))
    toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
    toolBar.isUserInteractionEnabled = true
    textField.inputAccessoryView = toolBar

Step 3 : Adding two buttons method which which is in ToolBar. One is doneClick and other is cancelClick.
func doneClick() {
    let dateFormatter1 = DateFormatter()
    dateFormatter1.dateStyle = .medium
    dateFormatter1.timeStyle = .none
    textField_Date.text = dateFormatter1.string(from:
func cancelClick() {
Step 4 : Calling the pickUpDate function in UITextField delegate method.
func textFieldDidBeginEditing(_ textField: UITextField) {
Step 5 : outPut UIDatePicker with ToolBar in UITextField.

Step 6 : Demo Project  


iOS9 UIDatePicker Example with UIToolBar in Swift 3.0. iOS9 UIDatePicker Example with UIToolBar in Swift 3.0. Reviewed by KIRIT MODI on 23:35:00 Rating: 5

No comments:

Powered by Blogger.