CalendarView选中日期显示异常排查及可滑动周历启动默认选中当前日期的实现咨询
我仔细看了你贴的代码,现在帮你解决启动默认选中当前日期的问题,顺便排查下可能导致选中显示异常的点:
一、核心问题:启动默认选中当前日期的实现步骤
初始化选中值为当前日期
在使用WeekCalendarView的父视图里,把绑定的选中日期初始值设为.now即可,比如:struct YourParentView: View { @State private var title = "" @State private var focusedWeek = WeekModel.current @State private var selectedDate: Date? = .now // 关键:初始化为当前日期 @State private var isDragging = false var body: some View { VStack { Text(title) WeekCalendarView($title, selection: $selectedDate, focused: $focusedWeek, isDragging: isDragging) } } }修复日期比较的粒度问题
你当前用date == selectedDate直接比较日期,但.now包含时分秒,而你生成的周历日期大概率是当天00:00的时间戳,直接相等判断会失效。要改用日历的粒度比较:
修改DayView里的选中判断逻辑:struct DayView: View { let date: Date @Binding var selectedDate: Date? var body: some View { VStack(spacing: 12) { Text(Calendar.dayNumber(from: date)) .font(.system(size: 16).bold()) .background { // 改成按天粒度比较 if let selected = selectedDate, Calendar.current.isDate(date, equalTo: selected, toGranularity: .day) { Circle() .foregroundStyle(Calendar.current.isDateInToday(date) ? .blue : .primary) .frame(width: 40, height: 40) } } } .foregroundStyle( // 同样调整前景色的判断逻辑 (selectedDate != nil && Calendar.current.isDate(date, equalTo: selectedDate!, toGranularity: .day)) ? .gray : Calendar.current.isDateInToday(date) ? Color.blue : .primary ) .font(.system(.body, design: .rounded, weight: .medium)) .onTapGesture { withAnimation(.easeInOut) { selectedDate = date } } } }
二、选中显示异常的排查点
检查周历初始化逻辑
确认WeekModel.current生成的周确实包含当前日期,你可以打印WeekModel.current.days数组,看是否包含.now对应的日期(按天粒度判断)。如果Calendar.nearestMonday或currentWeek的扩展逻辑有问题,会导致当前周不包含今天,自然无法默认选中。绑定值传递是否完整
检查selection绑定在WeekCalendarView→WeekView→DayView的传递是否正确,有没有在某个环节被意外重置或覆盖。比如WeekCalendarView的onChange(of: position)或onChange(of: selection)逻辑,是否会干扰选中值。滚动定位的同步
当选中日期切换到其他周时,WeekCalendarView里的onChange(of: selection)会自动把focused设为对应周,进而触发滚动定位。你可以添加打印日志,确认这个逻辑是否正常触发,确保选中日期所在的周能被正确加载并滚动到视野中。
内容来源于stack exchange

