如何基于FSCalendar选中日期(工作日/周末)切换展示不同时段?
解决FSCalendar选中不同日期(工作日/周末)切换时段的问题
你已经搞定了日期选中和判断工作日/周末的核心逻辑,现在只差最后一步——根据选中日期的类型动态更新时段数据源,我来给你一步步梳理解决方案:
第一步:改造时段生成方法,支持区分工作日/周末
你当前的generateTimeRange()只能生成固定时段,我们需要给它加个参数,让它能根据传入的isWeekend返回对应时段。首先要确保你的Halls模型里有工作日和周末各自的时段配置(比如如果之前只有工作日的firstStartTimeToIncreasePrice和firstEndTimeToIncreasePrice,需要新增周末对应的属性,比如weekendStartTime和weekendEndTime)。
修改后的方法如下:
func generateTimeRange(isWeekend: Bool) -> [String]? { var result: [String] = [] guard let hall = bookingHall else { return nil } // 根据日期类型选择对应的起止时间 let startTimeStr = isWeekend ? hall.weekendStartTime : hall.firstStartTimeToIncreasePrice let endTimeStr = isWeekend ? hall.weekendEndTime : hall.firstEndTimeToIncreasePrice guard var startTime = timeFormatter.date(from: startTimeStr) else { return nil } guard let endTime = timeFormatter.date(from: endTimeStr) else { return nil } while startTime <= endTime { result.append(timeFormatter.string(from: startTime)) startTime = Calendar.current.date(byAdding: .hour, value: 1, to: startTime)! } return result }
第二步:在日期选中时动态更新数据源
接下来在calendar(_:didSelect:at:)方法里,根据选中日期的isWeekend调用改造后的方法,重新生成时段数组并刷新CollectionView:
func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) { let selectedDate = dateFormatter.string(from: date) selectedDateLabel.text = "Дата: \(selectedDate)" configCollectionViewAndLabelIsHidden(collectionView: false, textLabel: true, subTextLabel: true) calendar.setCurrentPage(date, animated: true) let isWeekend = date.isWeekend // 根据日期类型重新生成时段数组 if let timeRange = generateTimeRange(isWeekend: isWeekend) { self.timeIntervalArray = timeRange // 更新带价格的数据源数组 self.allArrayTimesAndPrices = timeRange.map({ (time: $0, price: bookingHall?.price ?? 0) }) // 刷新CollectionView展示新时段 self.collectionView.reloadData() } else { // 处理生成失败的情况,比如清空数据源 self.allArrayTimesAndPrices = [] self.collectionView.reloadData() print("无法生成对应时段") } // 保留你的日志打印 print(isWeekend ? "weekend" : "weekdays") }
第三步:初始化默认时段(可选但推荐)
为了让页面加载时就显示当前日期对应的时段,在viewDidLoad里根据初始日期的类型初始化数据源:
override func viewDidLoad() { super.viewDidLoad() // 初始化时根据当前日期类型生成默认时段 let isCurrentDateWeekend = curDate.isWeekend if let timeRange = generateTimeRange(isWeekend: isCurrentDateWeekend) { self.timeIntervalArray = timeRange if let hall = bookingHall { allArrayTimesAndPrices = timeRange.map({ (time: $0, price: hall.price) }) } self.collectionView.reloadData() } else { // Handle error } }
核心逻辑说明
- 本质就是让
allArrayTimesAndPrices这个数据源数组跟着选中的日期动态变化,而不是只在页面初始化时生成一次。 - 每次选中新日期时,重新生成对应类型的时段数组,更新数据源后调用
reloadData(),CollectionView就会自动展示对应时段了。 - 记得确认你的
Halls模型里已经配置了周末的时段参数,不然生成的时段还是和工作日一致哦~
内容的提问来源于stack exchange,提问作者Dima
相关产品推荐
相关产品推荐

