我正在尝试在我的项目之一中使用FSCalendar选择日期范围。
我发现该库具有Swift版本,但是范围选择版本仅适用于Objective-C。所以我试图使用桥接,但是我无法在Swift中使用RangePickerViewController。
有人为Swift使用日期范围实现此库吗? (例如,我想选择2个日期作为飞行应用程序的范围,在这里我选择了“出发和回程”航类日期。)
最佳答案
尽管FSCalendar不直接支持范围选择,但它允许多项选择,这意味着您可以在某个时候自行处理范围选择。
因此,在viewDidLoad()
中,必须确保将日历的allowsMultipleSelection
属性设置为true
:
private weak var calendar: FSCalendar!
override func viewDidLoad() {
super.viewDidLoad()
calendar.allowsMultipleSelection = true
}
View Controller 应符合
FSCalendarDelegate
协议(protocol),以处理选择/取消选择范围的逻辑。到目前为止,我们需要声明该范围的拖曳日期(凝视日期和结束日期):
// first date in the range
private var firstDate: Date?
// last date in the range
private var lastDate: Date?
也是一个日期数组,用于保存
firstDate
和lastDate
之间的值日期:private var datesRange: [Date]?
然后将
didSelect date
和didDeselect date
委托(delegate)方法实现为:func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
// nothing selected:
if firstDate == nil {
firstDate = date
datesRange = [firstDate!]
print("datesRange contains: \(datesRange!)")
return
}
// only first date is selected:
if firstDate != nil && lastDate == nil {
// handle the case of if the last date is less than the first date:
if date <= firstDate! {
calendar.deselect(firstDate!)
firstDate = date
datesRange = [firstDate!]
print("datesRange contains: \(datesRange!)")
return
}
let range = datesRange(from: firstDate!, to: date)
lastDate = range.last
for d in range {
calendar.select(d)
}
datesRange = range
print("datesRange contains: \(datesRange!)")
return
}
// both are selected:
if firstDate != nil && lastDate != nil {
for d in calendar.selectedDates {
calendar.deselect(d)
}
lastDate = nil
firstDate = nil
datesRange = []
print("datesRange contains: \(datesRange!)")
}
}
func calendar(_ calendar: FSCalendar, didDeselect date: Date, at monthPosition: FSCalendarMonthPosition) {
// both are selected:
// NOTE: the is a REDUANDENT CODE:
if firstDate != nil && lastDate != nil {
for d in calendar.selectedDates {
calendar.deselect(d)
}
lastDate = nil
firstDate = nil
datesRange = []
print("datesRange contains: \(datesRange!)")
}
}
那
datesRange
方法呢?我没有在回答中提到它是为了使其更短,您要做的就是从this answer复制粘贴。
输出: