我有一个日历,当我选择一天时,我想选择一整行(一周)..这是我到目前为止的代码:
//When a date is selected
func calendar(_ calendar: JTAppleCalendarView, didSelectDate date: Date, cell: JTAppleCell?, cellState: CellState) {
selectTheWeek(of: date)
setupLayoutCell(cell: cell, cellState: cellState)
}
func selectTheWeek(of date: Date) {
let starOfTheWeek = date.startOfWeek()
let endOfTheWeeK = date.endOfWeek()
calendarCollectionView.selectDates(from: starOfTheWeek, to: endOfTheWeeK)
}
extension Date {
func startOfWeek() -> Date {
let calendar = Calendar.autoupdatingCurrent
let currentDateComponents = calendar.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)
return calendar.date(from: currentDateComponents)!
}
func endOfWeek() -> Date {
let cal = Calendar.autoupdatingCurrent
var component = DateComponents()
component.weekOfYear = 1
component.day = -1
return cal.date(byAdding: component, to: startOfWeek())!
}
}
问题是我有一个无限循环,而且原因很清楚。 但我不知道如何防止它。有什么帮助吗?
JTAppleCalender
是一个外部库。它是collectionView
的扩展名。
答案 0 :(得分:1)
您可以使用2种技术来打破循环。
<强>第一强>:
calendarViewselectDates(from: starOfTheWeek, to: endOfTheWeeK, triggerSelectionDelegate: false)
通过将triggerSelectionDelegate
设置为false,您的代理功能didSelect
将不会被调用。
<强>第二强>
如果您使用的是MasterBranch
代码(我将在一周左右发布),您可以知道您的选择是否程序员已启动 vs 用户启动。你知道这个 - &gt; cellState。
if cellState.selectionType == .programatic {
// ignore stuff
} else {
// Do stuff
}
您可以将此if语句放在shouldSelect
函数中。
答案 1 :(得分:0)
我知道这不是最好的解决方案,但它可以避免你的问题
//When a date is selected
var shouldSelectWeek = true
func calendar(_ calendar: JTAppleCalendarView, didSelectDate date: Date, cell: JTAppleCell?, cellState: CellState) {
if shouldSelectWeek{
selectTheWeek(of: date)
shouldSelectWeek = false
}
setupLayoutCell(cell: cell, cellState: cellState)
}
func selectTheWeek(of date: Date) {
let starOfTheWeek = date.startOfWeek()
let endOfTheWeeK = date.endOfWeek()
calendarCollectionView.selectDates(from: starOfTheWeek, to: endOfTheWeeK)
}
extension Date {
func startOfWeek() -> Date {
let calendar = Calendar.autoupdatingCurrent
let currentDateComponents = calendar.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)
return calendar.date(from: currentDateComponents)!
}
func endOfWeek() -> Date {
let cal = Calendar.autoupdatingCurrent
var component = DateComponents()
component.weekOfYear = 1
component.day = -1
return cal.date(byAdding: component, to: startOfWeek())!
}
答案 2 :(得分:0)
只需添加一个新的布尔变量,如var shouldIgnoreDateSelection = false
,然后你就可以了
func calendar(_ calendar: JTAppleCalendarView, didSelectDate date: Date, cell: JTAppleCell?, cellState: CellState) {
if shouldIgnoreDateSelection == false {
selectTheWeek(of: date)
}
setupLayoutCell(cell: cell, cellState: cellState)
}
func selectTheWeek(of date: Date) {
let starOfTheWeek = date.startOfWeek()
let endOfTheWeeK = date.endOfWeek()
shouldIgnoreDateSelection = true
calendarCollectionView.selectDates(from: starOfTheWeek, to: endOfTheWeeK)
shouldIgnoreDateSelection = false
}