在UIDatePicker swift 4

时间:2018-03-27 19:14:47

标签: ios swift xcode swift4

我正在尝试将datePicker的时间限制在09:00 AM到09:00 PM(21:00),时间间隔为30分钟。我已经尝试了所有已知的方法并且已经在互联网上搜索了很长时间。但我一无所获。 这是我写的代码

//datePicker.setDate(dateFormatter.date(from: "09.00")!, animated: true)
datePicker.maximumDate = Calendar.current.date(byAdding: .hour, value: -12, to: dateFormatter.date(from: "21.00")!) //)Calendar.current.date(byAdding: Calendar.Component.hour, value: 1, to: Date())
 datePicker.minimumDate = Calendar.current.date(byAdding: Calendar.Component.hour, value: -12, to: dateFormatter.date(from: "09.00")!)

但它没有用。请帮忙。

4 个答案:

答案 0 :(得分:2)

限制用户以便他只能选择9到12之间的日期,但会显示所有可用的选项,因为这是日期选择器视图的默认行为,但通过设置正确的 minimumDate maximumDate 用户只能在9到21之间选择。请尝试以下代码并告诉我它是否有效

如果您想显示您的选择时间,我会建议您更好地创建一个您想要显示的数组,因此用户只会从您将提供的数组中选择在这种情况下上午9点和晚上9点像[9:00,9:30,10:00,10:30,.....,21:00]并将该数组设置为普通选择器

datePicker.datePickerMode = .time // setting mode to timer so user can only pick time as you want 
datePicker.minuteInterval = 30  // with interval of 30 
let dateFormatter = DateFormatter()
dateFormatter.dateFormat =  "HH:mm"

let min = dateFormatter.date(from: "9:00")      //createing min time
let max = dateFormatter.date(from: "21:00") //creating max time
datePicker.minimumDate = min  //setting min time to picker
datePicker.maximumDate = max  //setting max time to picker

答案 1 :(得分:1)

您要放入minimumDatemaximumDate的值是当前日期的上午9点和晚上9点。当前日期是代码中缺少的日期

let cal = Calendar.current
let now = Date()  // get the current date and time (2018-03-27 19:38:44)
let components = cal.dateComponents([.day, .month, .year], from: now)  // extract the date components 28, 3, 2018
let today = cal.date(from: components)!  // build another Date value just with date components, without the time (2018-03-27 00:00:00)
datePicker.minimumDate = today.addingTimeInterval(60 * 60 * 9)  // adds 9h
datePicker.maximumDate = today.addingTimeInterval(60 * 60 * 21) // adds 21h

答案 2 :(得分:0)

你是否试图从故事板中实现这一目标?

尝试以下配置: enter image description here

来自代码:

let calendar = Calendar.current
var dateComponents = calendar.dateComponents([.day, .month, .year], from: Date())
dateComponents.setValue(9, for: .hour)
let minDate = Calendar.current.date(from: dateComponents)
dateComponents.setValue(21, for: .hour)
let maxDate = Calendar.current.date(from: dateComponents)

self.datePicker?.minimumDate = minDate
self.datePicker?.maximumDate = maxDate
self.datePicker?.minuteInterval = 30

答案 3 :(得分:0)

试试这个:

let now = Date()
datePicker.datePickerMode = .time
datePicker.minimumDate = Calendar.current.date(bySettingHour: 9, minute: 0, second: 0, of: now)
datePicker.maximumDate = Calendar.current.date(bySettingHour: 21, minute: 0, second: 0, of: now)
datePicker.minuteInterval = 30