Byte Byte - 1 year ago 113
Swift Question

Getting date/time from DatePicker in swift

I have created a separate class for Date Picker.

import UIKit

protocol MYDatePickerViewControllerDelegate {
func didFinishSelectingDate(selectedDate:NSDate)

class MYDatePickerViewController: UIViewController {

@IBOutlet weak var containerView: UIView!
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var navigationBar: UINavigationBar!

var datePickerDelegate : MYDatePickerViewControllerDelegate?
var customTransitioningDelegate: MYFadeInFadeOutTransitioning? = MYFadeInFadeOutTransitioning()

super.init(nibName: "MyDatePickerViewController", bundle: NSBundle.mainBundle())

transitioningDelegate = customTransitioningDelegate
modalPresentationStyle = .Custom
convenience init(withSelectedDate date: NSDate) {

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
deinit {
customTransitioningDelegate = nil

override func viewDidLoad() {

func setupViewControllerUI() {
containerView.tag = kContainerViewTag


@IBAction func doneButtonTapped(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
@IBAction func cancelButtonTapped(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)

Which I am presenting from a different viewController as

let timePickerViewController = MYDatePickerViewController()
presentViewController(timePickerViewController, animated: true, completion: nil)

it does present from bottom of screen as follows

enter image description here

Now I am trying to get the selected date when user tap the done button on datePicker. For that i am trying to create a delegate and get selecetd date from there. but could not.
I have implemneted the delegate of MYDatePickerViewController into my other ViewController as

in my viewDidLoad

let datePicker = YASDatePickerViewController()
datePicker.datePickerDelegate = self

and then

func didFinishSelectingDate(selectedDate: NSDate) {

But I am not getting the date, please guide me.

Answer Source

Try this While presenting from a different viewController as:

let timePickerViewController = MYDatePickerViewController()
timePickerViewController.datePickerDelegate = self
presentViewController(timePickerViewController, animated: true, completion: nil)

And in conform viewController to your protocol:

class ViewController: UIViewController, MYDatePickerViewControllerDelegate {

Rest looks fine!