在Swift中从DatePicker获取日期/时间

时间:2016-08-30 07:24:44

标签: ios swift delegates uidatepicker

我为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)
    }
}

我将从另一个viewController呈现为

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

它确实从屏幕底部出现如下

enter image description here

现在,当用户点击datePicker上的完成按钮时,我正试图获取所选日期。为此,我正在尝试创建一个委托并从那里获得selecetd日期。但不能。 我已将MYDatePickerViewController的委托实现为我的其他ViewController

在我的viewDidLoad

let datePicker = YASDatePickerViewController()
    datePicker.datePickerDelegate = self

然后

func didFinishSelectingDate(selectedDate: NSDate) {
    print(selectedDate)
}

但我没有得到约会,请指导我。

1 个答案:

答案 0 :(得分:1)

尝试此操作从另一个viewController呈现为:

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

符合viewController的协议:

class ViewController: UIViewController, MYDatePickerViewControllerDelegate {

休息看起来很好!