Swift下FSCalendar周模式选择日期后如何更新Header显示值
FSCalendar周模式Header不跟随选中日期更新问题解决方案
问题根因
FSCalendar在周模式下,默认Header显示的是当前页对应周的起始日期,和用户选中的日期没有绑定关系:
- 若选中的日期和当前页属于同一周,page不会触发切换,Header也不会自动更新
- 没有原生的属性可以直接设置Header显示选中的日期值
具体修改步骤
- 将FSCalendar实例从
setupFSCalendar方法的局部变量改为类全局属性,同时新增变量存储当前选中的日期:
// 类内部声明全局属性 var calendar: FSCalendar! var selectedDate: Date?
修改setupFSCalendar中的初始化代码:
// 把原代码中的 let calendar = FSCalendar(...) 替换为以下内容 self.calendar = FSCalendar(frame: CGRect(x: 0, y: 0, width: ViewCalendar.frame.width, height: 250)) // 其余原有配置项保持不变
- 修改选中日期的代理方法,存储选中日期并强制刷新Header:
func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) { self.selectedDate = date calendar.setCurrentPage(date, animated: true) // 原代码中的 calendar.select(date) 是冗余调用,可直接删除 calendar.reloadData() }
- 实现Header标题自定义的代理方法,指定Header显示当前选中的日期:
func calendar(_ calendar: FSCalendar, titleForHeaderIn month: Date) -> String? { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd MMMM yyyy EEEE" // 优先显示选中日期,未选中任何日期时显示默认的周起始日期 if let selected = self.selectedDate { return dateFormatter.string(from: selected) } else { return dateFormatter.string(from: month) } }
额外排查项
如果仅需要Header跟随周切换更新,不需要显示选中日期,可检查两个配置:
- 确认
calendar.firstWeekday = 2(周一为周起始)符合你的业务预期,周起始配置错误会导致日期的周归属计算异常,出现选中跨周日期但page不切换的问题 - 确保
setCurrentPage方法正常调用,若选中日期和当前页属于同一周,page不会触发切换,Header自然不会更新
内容的提问来源于stack exchange,提问作者Tekhe
相关产品推荐
相关产品推荐

