iOS Swift 3 - UIDatePicker

Posted

技术标签:

【中文标题】iOS Swift 3 - UIDatePicker【英文标题】: 【发布时间】:2017-03-21 22:02:16 【问题描述】:

我有一个UIDatePicker,它显示了日、月和年。但我不知道如何获取这些参数。

那么,使用 Swift 3 从UIDatePicker 获取日期、月份和年份的最佳方法是什么?

【问题讨论】:

您的问题不清楚 你能展示你尝试过的代码吗 你想从选择器中获取选定的日期? 你想要什么样的日期选择器,我的意思是说,无论你是想将日期选择器嵌入到你的文本字段中,还是只想用作屏幕上的弹出框 【参考方案1】:

Swift 3 和 Swift 4 中的 UIDatePicker 示例。

在 Swift 3 中你可以使用

    在 swift 3 中创建单视图应用程序的简单项目 拖动文本字段并连接到 viewController 日期选择器看起来像图片

    ViewController 代码如下。

      class ViewController: UIViewController 
         //Text Field Connection
       @IBOutlet weak var txtDatePicker: UITextField!
       //Uidate picker
       let datePicker = UIDatePicker()
    
        override func viewDidLoad() 
        super.viewDidLoad()
       //show date picker
         showDatePicker()
      
    
    
       func showDatePicker()
       //Formate Date
        datePicker.datePickerMode = .date
    
        //ToolBar
       let toolbar = UIToolbar();
       toolbar.sizeToFit()
    
       //done button & cancel button
        let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.bordered, target: self, action: "donedatePicker")
        let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
       let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.bordered, target: self, action: "cancelDatePicker")
       toolbar.setItems([doneButton,spaceButton,cancelButton], animated: false)
    
    // add toolbar to textField
    txtDatePicker.inputAccessoryView = toolbar
     // add datepicker to textField
    txtDatePicker.inputView = datePicker
    
       
    
     func donedatePicker()
      //For date formate
       let formatter = DateFormatter()
       formatter.dateFormat = "dd/MM/yyyy"
       txtDatePicker.text = formatter.string(from: datePicker.date)
       //dismiss date picker dialog
       self.view.endEditing(true)
        
    
          func cancelDatePicker()
           //cancel button dismiss datepicker dialog
            self.view.endEditing(true)
          
       
    

    完整源代码项目已提供给 github。 github链接:https://github.com/enamul95/DatePicker1

    在 Swift 4 或 5 中,您可以使用以下代码

     class ViewController: UIViewController 
    
       @IBOutlet weak var txtDatePicker: UITextField!
      let datePicker = UIDatePicker()
    
      override func viewDidLoad() 
        super.viewDidLoad()
         showDatePicker()
      
    
    
      func showDatePicker()
        //Formate Date
        datePicker.datePickerMode = .date
    
       //ToolBar
       let toolbar = UIToolbar();
       toolbar.sizeToFit()
       let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(donedatePicker));
       let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
      let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelDatePicker));
    
     toolbar.setItems([doneButton,spaceButton,cancelButton], animated: false)
    
      txtDatePicker.inputAccessoryView = toolbar
      txtDatePicker.inputView = datePicker
    
     
    
      @objc func donedatePicker()
    
       let formatter = DateFormatter()
       formatter.dateFormat = "dd/MM/yyyy"
       txtDatePicker.text = formatter.string(from: datePicker.date)
       self.view.endEditing(true)
     
    
     @objc func cancelDatePicker()
        self.view.endEditing(true)
      
    
    

【讨论】:

你也可以使用本地化的done和cancel bar按钮,如下(Swift 4,不知道3): let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: # selector(donedatePicker)) let cancelButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.cancel, target: self, action: #selector(cancelDatePicker))【参考方案2】:

在 Swift 3 中,您可以像这样使用DateComponents

首先在datepicker 上为.valueChanged 事件添加操作。

datepicker.addTarget(self, action: #selector(dateChanged(_:)), for: .valueChanged)

然后在操作中使用DateComponents 获取选定的日、月和年。

func dateChanged(_ sender: UIDatePicker) 
    let components = Calendar.current.dateComponents([.year, .month, .day], from: sender.date)
    if let day = components.day, let month = components.month, let year = components.year 
        print("\(day) \(month) \(year)")
    

【讨论】:

我没有注意到并错误地将我的操作注册到touchUpInside 事件。但是我应该为.valueChanged【参考方案3】:

假设如果您想在点击文本字段时显示 datePicker,并且当用户从中选择某个日期时,它将自动填充到您的文本字段中。

 @IBOutlet weak var dateTextField: UITextField!
let datePickerView:UIDatePicker = UIDatePicker()
        datePickerView.datePickerMode = UIDatePickerMode.date
        dateTextField.inputView = datePickerView
        datePickerView.addTarget(self, action: #selector(ViewController.datePickerValueChanged), for: UIControlEvents.valueChanged)

// Make a dateFormatter in which format you would like to display the selected date in the textfield.
func datePickerValueChanged(sender:UIDatePicker) 

        let dateFormatter = DateFormatter()

        dateFormatter.dateStyle = DateFormatter.Style.medium

        dateFormatter.timeStyle = DateFormatter.Style.none

        dateTextField.text = dateFormatter.string(from: sender.date)

    

这里 Sender.date 是 UIDatePicker 的实例,从日期选择器中获取日期并填充到您的文本字段中。

【讨论】:

我不知道 inputView... 赢得了这么多时间。谢谢!【参考方案4】:

创建UIDatePickerIBOutlet 并正确连接,然后使用下面的代码获取日、月、年等。

var comp = NSDateComponents()
@IBOutlet weak var datePicker: UIDatePicker!

override func viewDidLoad() 
    super.viewDidLoad()
    datePicker.addTarget(self, action: Selector("datePickerChanged:"), forControlEvents: UIControlEvents.ValueChanged)


func datePickerChanged(datePicker:UIDatePicker)
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
    dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
    let cal = NSCalendar.currentCalendar()
    comp = cal.components([.Era, .Day, .Month, .Year, .Hour, .Minute] , fromDate: datePicker.date)

    // getting day, month, year ect
    print ("Era:\(comp.era) Date:\(comp.day) Month:\(comp.month) Month:\(comp.year) Hours: \(comp.hour) Minuts:\(comp.minute)")

【讨论】:

OP 已在 Swift 3 中提出要求,因此击球手使用 DateComponents 而不是 NSDateComponentsCalendar 而不是 NSCalendar @NiravD 这是一个版本差异,无论如何感谢您在这里的贡献+一个也为您提供:) @vaibhav 没有从viewDidLoad 调用super 是一个严重错误。 @dirtydanee 刚刚纠正了格式化问题,super 已经存在。【参考方案5】:
var picker = UIDatePicker()
picker = UIDatePicker()
textField.inputView = picker
picker.addTarget(self, action: #selector(ViewController.handleDatePicker), for: UIControlEvents.valueChanged)
picker.datePickerMode = .date

func handleDatePicker() 
    var dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd-MM-yyyy"
    textfield.text = dateFormatter.string(from: picker.date)
    textfield.resignFirstResponder()

【讨论】:

【参考方案6】:

Swift 5 用户可以试试这个它对我有用

import UIKit

class FreeCallsViewController: UIViewController 

@IBOutlet weak var dateTextField: UITextField!

let datepicker = UIDatePicker()

override func viewDidLoad() 
    super.viewDidLoad()

    // Do any additional setup after loading the view.


@IBAction func calenderButtonPressed(_ sender: UIButton) 
    self.createDatePicker()


func createDatePicker() 
    let toolbar = UIToolbar()
    toolbar.sizeToFit()
    
    let donebtn = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donepressed))
    
    toolbar.setItems([donebtn], animated: true)
    
    dateTextField.inputAccessoryView = toolbar
    
    dateTextField.inputView = datepicker
    
    datepicker.datePickerMode = .date

@objc func donepressed() 
    let dateformator = DateFormatter()
    
    dateformator.dateStyle = .medium
    dateformator.timeStyle = .none
    
    
    
    dateTextField.text = dateformator.string(from: datepicker.date)
    self.view.endEditing(true)

【讨论】:

【参考方案7】:

问题可以通过多种方式解决。如果您正在寻找仅使用代码的解决方案:

    class Foo: UIViewController 
        // Lets create your picker - Can be IBOutlet too
        lazy var datePicker: UIDatePicker = 
            let picker = UIDatePicker()
            picker.datePickerMode = .date
            return picker
        ()

    override func viewDidLoad() 
        super.viewDidLoad()
        //Observe the value changes in datePickerValueChanged function for example
        datePicker.addTarget(self, action: #selector(datePickerValueChanged), for: .valueChanged)
    

    func datePickerValueChanged(sender: UIDatePicker) 
        // Function will be called every time picker changes it's value
        // You can access to it the following way
        print(sender.date)
    
  

如果您在 Interface Builder 中有 UIDatePicker,则另一种方式。你几乎需要同样的东西,就像上面一样,但我的方式略有不同。在 Interface Builder 中单击您的 UIDatePicker

您会在底部看到Value Changed 选项。现在你抓住 IBAction 并将其拖到你的 viewController 上,然后像这样设置你的连接:

这样您就可以实现与第一个示例相同的功能,因为您最终会得到几乎相同的功能:

@IBAction func datePickerValueChanged(sender: UIDatePicker) 
    print(sender.date)

【讨论】:

【参考方案8】:

Swift 5.0+

希望它对你有用,享受吧!

import UIKit

protocol SKUIDatePickerDelegate:class 
    func getDate(_ sKUIDatePicker:SKUIDatePicker, date:String)
    func cancel(_ sKUIDatePicker:SKUIDatePicker)


class SKUIDatePicker:UIView 
    
    private let datePicker = UIDatePicker()
    private var dateFormate = "yyyy/mm/dd"
    weak var delegate:SKUIDatePickerDelegate?
    
    override init(frame: CGRect) 
        super.init(frame: frame)
        // self.frame = UIScreen.main.bounds
    
    
    required init?(coder: NSCoder) 
        fatalError("init(coder:) has not been implemented")
    
    
    func showDatePicker(txtDatePicker:UITextField)
        //Formate Date
        datePicker.datePickerMode = .date
        
        //ToolBar
        let toolbar = UIToolbar();
        toolbar.sizeToFit()
        let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action:       #selector(donedatePicker));
        let spaceButton = UIBarButtonItem(barButtonSystemItem:       UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
        let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action:       #selector(cancelDatePicker));
        
        toolbar.setItems([doneButton,spaceButton,cancelButton], animated:       false)
        
        txtDatePicker.inputAccessoryView = toolbar
        txtDatePicker.inputView = datePicker
        
    
    
    @objc func donedatePicker()
        
        let formatter = DateFormatter()
        formatter.dateFormat = dateFormate
        let result = formatter.string(from: datePicker.date)
        self.delegate?.getDate(self, date: result)
        
    
    
    @objc func cancelDatePicker()
        self.delegate?.cancel(self)
    
    

用法

class ViewController: UIViewController,SKUIDatePickerDelegate 
    //Text Field Connection
    @IBOutlet weak var txtDatePicker: UITextField!
    
    private var skUIdatePicker:SKUIdatePicker?
    
    override func viewDidLoad() 
        super.viewDidLoad()
        skUIdatePicker = SKUIdatePicker()
        skUIdatePicker.delegate = self
        skUIdatePicker.showDatePicker(txtDatePicker:txtDatePicker)
    
    
    func getDate(_ sKUIDatePicker:SKUIDatePicker, date:String) 
        print(date)
        self.view.endEditing(true)
    
    func cancel(_ sKUIDatePicker:SKUIDatePicker)
        self.view.endEditing(true)
    

【讨论】:

以上是关于iOS Swift 3 - UIDatePicker的主要内容,如果未能解决你的问题,请参考以下文章

Swift 3 iOS 兼容性

Swift 3 - iOS 11.2 上的 UICollectionview 问题

swift 3 ios:UILabel

iOS -Swift 3.0 -for(循环语句用法)

iOS Swift 3架构问题

iOS Swift 3 open