Swift - UIDatePicker

作者: iOS分享 | 来源:发表于2019-01-07 00:18 被阅读0次
    import UIKit
    
    class ViewController: UIViewController{
        override func viewDidLoad() {
            super.viewDidLoad()
            //创建DatePicker
            let datePicker = UIDatePicker()
            //设置位置
            datePicker.center = self.view.center
            //设置tag(可通过tag来获取其对象)
            datePicker.tag = 1
            //设置显示模式为日期时间
            datePicker.datePickerMode = UIDatePicker.Mode.dateAndTime
            //设置最大值,最小值
            datePicker.maximumDate = Date(timeInterval:3*24*60*60,since:Date())//设置最大值为现在时间往后三天以内
            datePicker.minimumDate = Date()//设置最小值为现在
            //添加到视图中
            self.view.addSubview(datePicker)
            //添加确定按钮
            let button = UIButton(frame: CGRect(x: 50, y: 400, width: 250, height: 50))
            button.backgroundColor = UIColor.yellow
            button.setTitle("确定", for: .normal)
            button.addTarget(self, action: #selector(ViewController.getValue), for: .touchUpInside)
            self.view.addSubview(button)
        }
        @objc func getValue()
        {
            let datePicker = self.view.viewWithTag(1)as! UIDatePicker//通过tag获取datePicker对象
            let date = datePicker.date//获取选定的值
            //初始化日期格式化对象
            let dateFormatter = DateFormatter()
            //设置日期格式化对象的具体格式
            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
            //将选定的值转换为string格式以设定格式输出
            let dateAndTime = dateFormatter.string(from: date)
            print(dateAndTime)
        }
    }
    
    

    相关文章

      网友评论

        本文标题:Swift - UIDatePicker

        本文链接:https://www.haomeiwen.com/subject/ykqyrqtx.html