no

How to display a Date using TextField with Swift

Displaying Date with TextField Click with Swift First you must have a textfield connected to storyboard. @IBOutlet   weak   var  txtFie...

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
 }

Related

xcode 6947232669051911233

Post a Comment Default Comments

item