IOS控件-UIDatePicker日期选择器
创建一个DatePicker控件
1 | let datePicker = UIDatePicker() |
2 | //设置日期拾取器对象的中心点位置 |
3 | datePicker.center = CGPoint(x: 160, y: 200) |
4 | datePicker.tag=1 |
5 | //设置日期*小值 |
6 | datePicker.minimumDate=Date() |
7 | //*大值为之后的三天 |
8 | datePicker.minimumDate = Date(timeInterval: 3*24*60*60, since: Date()) |
9 | self.view.addSubview(datePicker) |
添加一个button
1 | let button=UIButton(frame: CGRect(x: 20, y: 360, width: 280, height: 44)) |
2 | button.setTitle(“get date”, for: UIControlState()) |
3 | button.backgroundColor=UIColor.brown |
4 | button.addTarget(self, action: #selector(ViewController.showDatePicker(_ :)), for: UIControlEvents.touchUpInside) |
5 | self.view.addSubview(button) |
绑定一个点击事件
1 | @objc func showDatePicker(_ button:UIButton){ |
2 | //通过tag找到datePicker |
3 | let datePicker=self.view.viewWithTag(1) as! UIDatePicker |
4 | //获得datePicker的日期值 |
5 | let date=datePicker.date |
6 | //新建一个日期格式化对象 用来格式化日期 |
7 | let dateFormatter = DateFormatter() |
8 | //设置日期的格式 |
9 | dateFormatter.dateFormat=”yyyy–MM–dd HH:mm” |
10 | //将日期转换为指定字符串 |
11 | let dateAndTime = dateFormatter.string(from: date) |
12 | |
13 | let dialog = UIAlertController(title: “title”, message: dateAndTime, preferredStyle: UIAlertControllerStyle.alert) |
14 | let ok = UIAlertAction(title: “ok”, style: UIAlertActionStyle.default, handler: nil) |
15 | dialog.addAction(ok) |
16 | self.present(dialog,animated: true,completion: nil) |
17 | } |