iOS9 UIDatePicker Example with UIToolBar in Swift.

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:CGRectMake(0, 0, self.view.frame.size.width, 216))
    self.datePicker.backgroundColor = UIColor.whiteColor()
    self.datePicker.datePickerMode = UIDatePickerMode.Date
    textField.inputView = self.datePicker

    // ToolBar
    let toolBar = UIToolbar()
    toolBar.barStyle = .Default
    toolBar.translucent = 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: "doneClick")
    let spaceButton = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
    let cancelButton = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: "cancelClick")
    toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
    toolBar.userInteractionEnabled = 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 = NSDateFormatter()
        dateFormatter1.dateStyle = .MediumStyle
        dateFormatter1.timeStyle = .NoStyle
        textField_Date.text = dateFormatter1.stringFromDate(
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. iOS9 UIDatePicker Example with UIToolBar in Swift. Reviewed by Kirit Modi on 23:35:00 Rating: 5

No comments:

Powered by Blogger.