我想使用带有空选项的日期选择器。就像用户不想选择日,月或年一样,会有一个选项“ - ”(空)。
这是一个更好理解的图像
您无法更改UIDatePicker的值。如果要在行上显示自定义值,可以使用UIPickerView。显示月份和“ - ”的示例代码是:
let months: [String] = ["-" ,"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"]
let pickerView: UIPickerView = UIPickerView()
pickerView.delegate = self
pickerView.dataSource = self
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return months.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return months[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
// do whatever you want when specific row is selected
}
对于这种方式,您需要使用DATE PICKER VIEW,这样您就可以使用Picker View,并手动设置日期。
例如:
var monthsArray = ["-", "May", "June", "...", "December"]
var yearsArray = ["-", "2018", "2017", "2016", "...."]
var daysArray = ["1", "2", "-", "3", "4"]