Using Swift with UIKit to Develop iPhone Apps: 04 Selecting a Date Using Date Picker

In this course, you will learn how to select dates in an iPhone app using the Swift language and the UIKit framework. Specifically, we will explain the basic way to use UIDatePicker to allow users to select the desired date and time and handle it within the app. This course will proceed step by step to be understandable for both beginners and intermediate developers.

1. What is UIDatePicker?

UIDatePicker is a UI component of UIKit that helps the user select a date or time. Using this component makes it more intuitive and reduces errors when compared to having the user input the values directly. UIDatePicker is provided in the following formats:

  • Date Picker
  • Time Picker
  • Date and Time Picker

You can set a date or time as the sole selection option, and it can be set up very simply. In the following section, we will explain how to use UIDatePicker to select dates.

2. Project Setup

To develop an iOS app, you need to use Xcode. Here’s how to create a new project using Xcode:

  1. Open Xcode and select “Create a new Xcode project”.
  2. Select “App” under the iOS tab and click “Next”.
  3. Enter the project name and other details, then click “Next”.
  4. Select a location to save the project and click “Create”.

Now, the new Xcode project is ready. We will learn how to set up the UI with UIKit and add the UIDatePicker.

3. Adding UIDatePicker

To add a UIDatePicker to the storyboard, follow these steps:

  1. Open the storyboard file and select the desired View Controller.
  2. Search for Date Picker in the “Object Library” in the right panel.
  3. Drag the Date Picker to add it to the View Controller.
  4. Adjust the position and size of the Date Picker.

3.1 Setting UIDatePicker Properties

To set the properties of the added UIDatePicker, follow these steps:

  1. Select the Date Picker and click “Attributes Inspector” in the right panel.
  2. Choose either “Date” or “Date and Time” in the Mode to set the desired selection mode.
  3. You can set the Minimum Date and Maximum Date to limit the date range that the user can select.

4. Connecting UIDatePicker with Swift

Once the UIDatePicker is added to the UI, you need to connect it with IBOutlet and IBAction to interact with it. Here’s how to connect them:

4.1 Connecting IBOutlet

Connect the IBOutlet so that you can use the UIDatePicker in the code. Follow these steps:

  1. Open the Assistant Editor and display the ViewController.swift file alongside the storyboard.
  2. While holding the Ctrl key, drag the UIDatePicker from the storyboard to ViewController.swift.
  3. Enter the outlet name and click “Connect”.

Now that the IBOutlet is connected, you can use the UIDatePicker in your code.

4.2 Connecting IBAction

Connect an IBAction to create a method that gets called when the value of the UIDatePicker changes. Follow these steps:

  1. Select the Date Picker, then keep the Assistant Editor open with ViewController.swift.
  2. While holding the Ctrl key, drag the Date Picker from the storyboard to ViewController.swift.
  3. Select the Action type and set the method name, then click “Connect”.
class ViewController: UIViewController {

    @IBOutlet weak var datePicker: UIDatePicker!
    
    @IBAction func datePickerChanged(_ sender: UIDatePicker) {
        let selectedDate = sender.date
        print("Selected date: \(selectedDate)")
    }
}

Now, every time the user changes the value of the Date Picker, the selected date will be printed in the console.

5. Formatting the Date

You may need to convert the selected date into a format that is understandable for the user. To do this, you can use the DateFormatter class. Here’s how to implement it:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm" // Set your desired format
let formattedDate = dateFormatter.string(from: selectedDate)
print("Formatted date: \(formattedDate)")

6. Checking the Final Result

Once all settings are complete, run the app on a simulator or a real device to check whether the Date Picker works correctly. You will be able to confirm that the selected date is printed in the console when the user selects a date.

7. Implementing Additional Features

Now that you have learned the basics of using UIDatePicker, let’s implement some additional features. Some functionalities that can be implemented after selecting a date include:

  • Displaying the selected date in a UILabel
  • Saving the date to use it on other screens
  • Executing events based on specific date selections (e.g., creating a basic day counter)

7.1 Displaying the Date in UILabel

You can add a UILabel to display the selected date. First, add a UILabel in the storyboard and connect it via IBOutlet. Then, add the following code:

@IBOutlet weak var dateLabel: UILabel!

@IBAction func datePickerChanged(_ sender: UIDatePicker) {
    let selectedDate = sender.date
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
    dateLabel.text = "Selected date: \(dateFormatter.string(from: selectedDate))"
}

7.2 Saving the Date

You can use NSUserDefaults to save the selected date and retrieve it when the app is restarted. You can implement it by adding the following code:

func saveDate(date: Date) {
    UserDefaults.standard.set(date, forKey: "savedDate")
}

func loadDate() {
    if let date = UserDefaults.standard.object(forKey: "savedDate") as? Date {
        datePicker.date = date
        dateLabel.text = "Saved date: \(dateFormatter.string(from: date))"
    }
}

Call the loadDate() method when the app launches to display the saved date on the UILabel and UIDatePicker if available.

8. Conclusion

In this course, we learned how to select dates using UIDatePicker with Swift and the UIKit framework. We explored the basic usage, date formatting, and how to implement additional features. UIDatePicker is a very useful tool for selecting dates and times and is widely used in various apps. Now you are equipped with the ability to develop your own app with features utilizing UIDatePicker.

Additionally, for a deeper understanding of the Swift language and UIKit, it is advisable to learn through official documentation or courses. Wishing you success on your future development journey!