Learn-iOS-Swift-by-Examples/UICatalog/Swift/UIKitCatalog/DatePickerController.swift

69 lines
1.8 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this samples licensing information
Abstract:
A view controller that demonstrates how to use UIDatePicker.
*/
import UIKit
class DatePickerController: UIViewController {
// MARK: - Properties
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var dateLabel: UILabel!
/// A date formatter to format the `date` property of `datePicker`.
lazy var dateFormatter: NSDateFormatter = {
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .MediumStyle
dateFormatter.timeStyle = .ShortStyle
return dateFormatter
}()
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
configureDatePicker()
}
// MARK: - Configuration
func configureDatePicker() {
datePicker.datePickerMode = .DateAndTime
/*
Set min/max date for the date picker. As an example we will limit the
date between now and 7 days from now.
*/
let now = NSDate()
datePicker.minimumDate = now
let currentCalendar = NSCalendar.currentCalendar()
let dateComponents = NSDateComponents()
dateComponents.day = 7
let sevenDaysFromNow = currentCalendar.dateByAddingComponents(dateComponents, toDate: now, options: [])
datePicker.maximumDate = sevenDaysFromNow
datePicker.minuteInterval = 2
datePicker.addTarget(self, action: #selector(DatePickerController.updateDatePickerLabel), forControlEvents: .ValueChanged)
updateDatePickerLabel()
}
// MARK: - Actions
func updateDatePickerLabel() {
dateLabel.text = dateFormatter.stringFromDate(datePicker.date)
}
}