Looking for a JavaEE Architect or Potential Tech Co-Founder?
Please don't hesitate to contact me.

How to display a Date with TextField Click with Swift

Displaying Date with TextField Click with Swift

First you must have a textfield connected to storyboard.


@IBOutlet weak var txtField_helloDatePicker: UITextField!

Next you should have a constant of UIDatePicker type.

let datePicker = UIDatePicker()

Then inside the viewDidLoad function, you should set the date picker mode to date

datePicker.datePickerMode = UIDatePickerMode.Date

Then to show the date picker on tapping the textfield, you should set the input view of that textfield to the date picker
        
txtField_helloDatePicker.inputView = datePicker

Then to manage the changes in the selection
        

datePicker.addTarget(self, action: Selector("datePickerChanged:"), forControlEvents: UIControlEvents.ValueChanged)

Then to handle the action  of the date picker, you should have 

func datePickerChanged(datePicker:UIDatePicker) {
        println("time picker changed for ceremony")
        
        var dateFormatter = NSDateFormatter()
        
        dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
        
        var strDate = dateFormatter.stringFromDate(datePicker.date)
        
        txtField_helloDatePicker.text = strDate
 }

Summary of Code:

datePicker.datePickerMode = UIDatePickerMode.Date
        
txtField_helloDatePicker.inputView = datePicker
        
datePicker.addTarget(self, action: Selector("datePickerChanged:"), forControlEvents: UIControlEvents.ValueChanged)

func datePickerChanged(datePicker:UIDatePicker) {
        println("time picker changed for ceremony")
        
        var dateFormatter = NSDateFormatter()
        
        dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
        
        var strDate = dateFormatter.stringFromDate(datePicker.date)
        
        txtField_helloDatePicker.text = strDate
 }
How to display a Date with TextField Click with Swift How to display a Date with TextField Click with Swift Reviewed by Edmond Legaspi on Wednesday, January 28, 2015 Rating: 5

No comments:

Powered by Blogger.