Updating label from datepicker ios swift

This tutorial is updated for x code 7.3 & swift 2.2

For collecting date, time & countdown timer we use datepicker in ios.

1. Open x code & create new x code project. Select single view application under IOS. Then fill in the following info.

 

new x code project

2. Go to main storyboard and select view controller. Set its size to iPhone 4”

size iphone 4 inch

 

3. Add label and datepicker in the storyboard.

datepicker & label

4. Set labels width to 150

label width

 

5. Set datepickers mode to date

datepicker mode

 

6. Open assistant editor with view controller & main storyboard view. Control drag label to view controller swift file.

label as outlet

 

7. Control drag datepicker to view controller swift file.

datepicker as outlet

 

8. Add following line to view did load section in view controller swift file.

// 8
datePicker.addTarget(self, action: #selector(ViewController.datePickerValueChanged), forControlEvents: UIControlEvents.ValueChanged)

9. Now every time the value of date picker changes it will execute method called datePickerValueChanged. So now we have to define the method as following

    // 9
    func datePickerValueChanged (datePicker: UIDatePicker) {

    let dateformatter = NSDateFormatter()

    dateformatter.dateStyle = NSDateFormatterStyle.MediumStyle
    dateformatter.timeStyle = NSDateFormatterStyle.NoStyle

    let dateValue = dateformatter.stringFromDate(datePicker.date)

    dateLabel.text = dateValue

}

10. Now run the project in iPhone 5s. When you change the values from date picker the label gets updated.

Screen Shot 2015-02-27 at 4.43.22 pm
Download X code file for datepicker to label

Total 2 Votes
0

Tell us how can I improve this tutorial?

+ = Verify Human or Spambot ?