1, using storyboard to create a date selection controlFirst we add a Uidatepicker control and a button directly to the Main.storyboard. This button is for the pop-up prompt when clicked to display the date and time of the current selection. Also use Iboutlet to establish the association of controls and events in Viewcontroller.swift, with the following code:
123456789101112131415161718192021222324252627282930 |
class ViewController
:
UIViewController {
@IBOutlet
var dpicker:
UIDatePicker
!
@IBOutlet
var btnshow:
UIButton
!
override func viewDidLoad() {
super
.viewDidLoad()
}
@IBAction func showClicked(sender:
UIButton
)
{
var date = dpicker.date
// 创建一个日期格式器
var dformatter =
NSDateFormatter
()
// 为日期格式器设置格式字符串
dformatter.dateFormat =
"yyyy年MM月dd日 HH:mm:ss"
// 使用日期格式器格式化日期、时间
var datestr = dformatter.stringFromDate(date)
var message =
"您选择的日期和时间是:\(datestr)"
// 创建一个UIAlertView对象(警告框),并通过该警告框显示用户选择的日期、时间
let alertView =
UIAlertView
()
alertView.title =
"当前日期和时间"
alertView.message = message
alertView.addButtonWithTitle(
"确定"
)
alertView.show()
}
}
|
2, Pure code creation date selection control
12345678910111213141516171819202122232425262728293031 |
import UIKit
class ViewController
:
UIViewController {
override func viewDidLoad() {
super
.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//创建日期选择器
var datePicker =
UIDatePicker
(frame:
CGRectMake
(0.0, 0.0, 320.0, 216.0))
//将日期选择器区域设置为中文,则选择器日期显示为中文
datePicker.locale =
NSLocale
(localeIdentifier:
"zh_CN"
)
//注意:action里面的方法名后面需要加个冒号“:”
datePicker.addTarget(
self
, action:
"dateChanged:"
,
forControlEvents:
UIControlEvents
.
ValueChanged
)
self
.view.addSubview(datePicker)
}
//日期选择器响应方法
func dateChanged(datePicker :
UIDatePicker
){
//更新提醒时间文本框
let formatter =
NSDateFormatter
()
//日期样式
formatter.dateFormat =
"yyyy年MM月dd日 HH:mm:ss"
println
(formatter.stringFromDate(datePicker.date))
}
override func didReceiveMemoryWarning() {
super
.didReceiveMemoryWarning()
}
}
|
3, date selection control text changed to Chinese
The text in the default date selection control is in English, and if you want to display Chinese, you need to set the area of the date selection control as follows
12 |
//将日期选择器区域设置为中文,则选择器日期显示为中文 datePicker.locale = NSLocale (localeIdentifier: "zh_CN" ) |
Use of Swift-date selection control (Uidatepicker)