Byte Byte - 3 months ago 19
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()

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

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

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

override func viewDidLoad() {
super.viewDidLoad()
setupViewControllerUI()
}

func setupViewControllerUI() {
containerView.tag = kContainerViewTag

}

@IBAction func doneButtonTapped(sender: AnyObject) {
datePickerDelegate?.didFinishSelectingDate(self.datePicker.date)
print(self.datePicker.date)
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) {
print(selectedDate)
}


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

Answer

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!

Comments