// // DatePickerPopupView.swift // MTP2_iOS // // Created by zhongyuan on 2018/6/5. // Copyright © 2018年 zhongyuan.All rights reserved. // import UIKit protocol DatePickerPopupViewDelegate: class { /// 给页面上textfield赋值 /// /// - Parameters: /// - sender: DatePickerPopupView /// - date: 当前选择的日期 /// - value: 当前选择的值 func datePickerPopupView(_ sender: DatePickerPopupView,selectedDate date: Date, selectedDateString value: String) } class DatePickerPopupView: UIView { /// 时间选择器 @IBOutlet weak var datePicker: UIDatePicker! /// 遮罩视图 @IBOutlet weak var maskPopupView: UIView! /// 弹出框有效组件的背景view @IBOutlet weak var backgroundView: UIView! @IBOutlet weak var heightConstraint: NSLayoutConstraint! //MARK: TAG值 /// 取消按钮tag private static let CANCELBUTTONTAG = 100 /// 确认按钮tag private static let CONFIRMBUTTONTAG = 101 /// delegate weak var delegate: DatePickerPopupViewDelegate? /// 选择日期的String值 private var value = "" @IBAction func buttonOnPressed(_ sender: UIBarButtonItem) { switch sender.tag { case DatePickerPopupView.CANCELBUTTONTAG: hidePopupView() case DatePickerPopupView.CONFIRMBUTTONTAG: if value == "" { valueChange(datePicker: datePicker) } delegate?.datePickerPopupView(self, selectedDate: datePicker.date, selectedDateString: value) default: break } } override func awakeFromNib() { super.awakeFromNib() bulidView() } /// 初始化设置 private func bulidView() { /// 设置frame setNeedsLayout() layoutIfNeeded() /// 单击手势 let ges = UITapGestureRecognizer(target: self, action: #selector(hidePopupView)) self.maskPopupView.addGestureRecognizer(ges) /// datePicker datePicker.locale = Locale(identifier: "zh_cn") datePicker.timeZone = NSTimeZone.system datePicker.datePickerMode = .date datePicker.layer.backgroundColor = UIColor.white.cgColor datePicker.layer.masksToBounds = true datePicker.addTarget(self, action: #selector(valueChange(datePicker:)), for: .valueChanged) } /// 展示时间选择框 /// /// - Parameters: /// - currentDate: 当前显示的时间 /// - minimumDate: 可选择的最小时间 func showInView(_ superView: UIView, currentDate: Date, minimumDate: Date? = nil, maximumDate: Date? = nil) { datePicker.date = currentDate datePicker.minimumDate = minimumDate datePicker.maximumDate = maximumDate superView.addSubview(self) self.heightConstraint.constant = 261.5 UIView.animate(withDuration: 0.3, animations: { self.layoutIfNeeded() }) self.frame = superView.frame } /// 移除当前 view @objc func hidePopupView() { self.heightConstraint.constant = 0 UIView.animate(withDuration: 0.3, animations: { self.layoutIfNeeded() }) { (isSuccess) in self.removeFromSuperview() } } @objc func valueChange(datePicker: UIDatePicker) { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" let dateString = formatter.string(from: datePicker.date) value = dateString } }