swift 4.2实现日期选择器

swift 4.2实现日期选择器

代码:

import UIKit

class ViewController: UIViewController {
    var datePicker: UIDatePicker!
    var label: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
  
        let screen = UIScreen.main.bounds
        
        //1. 日期选择器
        let datePickerWidth: CGFloat = 320
        let datePickerHeight: CGFloat = 167
        
        self.datePicker = UIDatePicker(frame: CGRect(x: 0, y: 0, width: datePickerWidth, height: datePickerHeight))
        self.datePicker.locale = NSLocale(localeIdentifier: "zh-Hans") as Locale //设置为简体中文
        //设置日期时间模式,其他选择项还有 .date  .time  .countDownTimer(倒计时定时器)
        self.datePicker.datePickerMode = .dateAndTime
        self.view.addSubview(self.datePicker)

        //2. 添加标签
        let labelWidth: CGFloat = 200
        let labelHeight: CGFloat = 21
        let labelTopView: CGFloat = 281
        self.label = UILabel(frame: CGRect(x: (screen.size.width - labelWidth)/2, y: labelTopView, width: labelWidth, height: labelHeight))
        self.label.text = "Label"
        self.label.textAlignment = .center
        self.view.addSubview(self.label)



        //3.button代码实现
        let button = UIButton(type: UIButton.ButtonType.system)
        button.setTitle("OK", for: UIControl.State.normal)
        let buttonWidth: CGFloat = 46
        let buttonheight: CGFloat = 30
        let buttonTopView: CGFloat = 379
        button.frame = CGRect(x: (screen.size.width - buttonWidth)/2, y: buttonTopView, width: buttonWidth, height: buttonheight)
        //addTarget,第一个参数是事件处理者,第二个参数是选择器类型,它指向事件处理方法,第三个参数是事件.
        button.addTarget(self, action: #selector(onclick(sender:)), for: UIControl.Event.touchUpInside)
        self.view.addSubview(button)
    
}
    
    @objc func onclick(sender:AnyObject){
        let theDate : Date = self.datePicker.date
        let desc = theDate.description(with: Locale.current)
        NSLog("the date formate is %@ ", desc)
        
        let dateFormatter : DateFormatter = DateFormatter()
        dateFormatter.dateFormat = "YYYY-MM-dd HH:mm:ss"
        NSLog("the date formate is: %@", dateFormatter.string(from: theDate))
        
        self.label.text = dateFormatter.string(from: theDate)
    }
    
    
}

image.png