@IBOutlet weak var tvDueDate: UITextField!
@IBOutlet weak var dateText: UITextField!
var datePicker = UIDatePicker()
var dayPicker = UIDatePicker()
let dateFormatter = NSDateFormatter()
let timeFormatter = NSDateFormatter()
var date_time:String!
var timeAs_24Hour:String!
var selected_date:String!
var timeAs_12Hour:String!
override func viewDidLoad() {
super.viewDidLoad()
setupDatePicker()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func setupDatePicker() {
datePicker.datePickerMode = .Time
dayPicker.datePickerMode = .Date
let toolBar = UIToolbar()
toolBar.barStyle = .Default
toolBar.translucent = true
toolBar.tintColor = UIColor.blueColor()
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(title: "Done", style: .Plain, target: self, action: #selector(ViewController.doneClick))
let spaceButton = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: #selector(ViewController.cancelClick))
toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.userInteractionEnabled = true
tvDueDate.inputView = datePicker
tvDueDate.inputAccessoryView = toolBar
tvDueDate.tintColor = UIColor.clearColor()
dateText.inputView = dayPicker
dateText.inputAccessoryView = toolBar
dateText.tintColor = UIColor.clearColor()
}
func doneClick() {
dateFormatter.dateFormat = "yyyy-MM-dd"
timeFormatter.dateFormat = "hh:mm a"
dateFormatter.dateStyle = .MediumStyle
let selected_Final_Date = dateFormatter.stringFromDate(dayPicker.date)
let selected_Final_Time = timeFormatter.stringFromDate(datePicker.date)
self.dateText.text = selected_Final_Date.uppercaseString
self.tvDueDate.text = selected_Final_Time.uppercaseString
tvDueDate.resignFirstResponder()
dateText.resignFirstResponder()
}
func cancelClick() {
tvDueDate.resignFirstResponder()
dateText.resignFirstResponder()
}
我正在使用Swift,并尝试在2个文本字段点击上创建2个选择器视图。在第一个文本字段中,它打开所有日期的月份,在2日它显示时间。我想在第一个文本字段点击显示当前日期和所有即将到来的日期,在第二个文本字段上,它应显示上午9点到下午6点之间的时间,只有30分钟差异,如9,9:30,10:00,10 :30,11:00,11:30。
答案 0 :(得分:0)
你应该使用UIDatePicker(或两个,如果你决定在一个字段中选择日期而在另一个字段中选择时间)
它们专为完全此目的而设计。
它们具有设置,可让您确定用户是选择日期,日期和时间,还是仅选择时间。它们还具有设置,允许您限制用户可以选择的日期或时间范围。 Xcode文档是一件很棒的事情。你应该试一试。