UIDatePicker
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let dataPicker = UIDatePicker()
dataPicker.center = CGPoint(x: 160, y: 200)
dataPicker.tag = 1
dataPicker.datePickerMode = UIDatePicker.Mode.dateAndTime
dataPicker.minimumDate = Date()
dataPicker.maximumDate = Date(timeInterval: 3*24*60*60, since: Date())
self.view.addSubview(dataPicker)
let button = UIButton(type: .roundedRect)
button.frame = CGRect(x: 20, y: 360, width: 280, height: 44)
button.setTitle("Get Date", for: .normal)
button.addTarget(self, action: #selector(getDateTime), for: .touchUpOutside)
self.view.addSubview(button)
}
@objc func getDateTime() {
let datePicker = self.view.viewWithTag(1) as! UIDatePicker
let date = datePicker.date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
let dateAndTime = dateFormatter.string(from: date)
print(dateAndTime)
}
}
网友评论