You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Swift的FSCalendar中将事件标记从圆点改为圆形?

实现FSCalendar环绕日期的圆形事件标记

我明白你想把FSCalendar默认的底部圆点事件标记改成环绕日期的圆形样式,这个需要自定义日历单元格的渲染逻辑,下面给你一套可行的实现方案:

步骤1:关闭默认事件标记

首先要隐藏FSCalendar自带的底部圆点,避免和我们自定义的圆形标记冲突:

// 在日历初始化或者viewDidLoad中设置
calendar.appearance.eventDefaultColor = .clear
calendar.appearance.eventSelectionColor = .clear

步骤2:自定义单元格的圆形标记

实现FSCalendar的cellFor代理方法,在单元格中添加环绕日期的圆形边框。这里要注意处理单元格复用的问题,避免滚动时重复添加标记:

func calendar(_ calendar: FSCalendar, cellFor date: Date, at position: FSCalendarMonthPosition) -> FSCalendarCell {
    // 获取复用的单元格(如果使用自定义单元格,替换为你的自定义类)
    let cell = calendar.dequeueReusableCell(withIdentifier: "FSCalendarCell", for: date, at: position)
    
    // 移除之前复用单元格中可能残留的标记视图
    cell.contentView.subviews.forEach { subview in
        if subview.tag == 1001 { // 给自定义标记设置唯一tag
            subview.removeFromSuperview()
        }
    }
    
    // 获取当前日期的事件数量
    let dateKey = date.GetFormatedDateAsString(format: "dd.MM.yyyy") // 注意:建议用小写yyyy,大写YYYY是周年可能导致匹配错误
    let eventCount = Events[dateKey] ?? 0
    
    if eventCount > 0 {
        // 创建圆形边框视图
        let labelFrame = cell.titleLabel.frame
        let circleView = UIView(frame: CGRect(
            x: labelFrame.origin.x - 2,
            y: labelFrame.origin.y - 2,
            width: labelFrame.width + 4,
            height: labelFrame.height + 4
        ))
        circleView.layer.borderColor = UIColor.systemBlue.cgColor // 自定义边框颜色
        circleView.layer.borderWidth = 1.5 // 边框粗细
        circleView.layer.cornerRadius = circleView.frame.width / 2
        circleView.backgroundColor = .clear // 保持透明,只显示边框
        circleView.tag = 1001
        
        // 将圆形视图放在日期标签下方,避免遮挡文字
        cell.contentView.insertSubview(circleView, belowSubview: cell.titleLabel)
        
        // 处理选中状态的样式(可选)
        if cell.isSelected {
            circleView.layer.borderColor = UIColor.white.cgColor // 选中时边框变白,配合日历选中背景
        }
    }
    
    return cell
}

步骤3:处理选中状态的动态更新(可选)

如果需要在选中日期时实时更新圆形标记的样式,可以补充实现didSelect代理方法:

func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
    // 刷新选中日期的单元格
    calendar.reloadDates([date])
}

注意事项

  • 确保你的GetFormatedDateAsString方法格式化后的字符串和Events字典的键完全匹配,建议使用yyyy而不是YYYY,因为大写的YYYY代表“周年”,可能会在跨年周出现日期匹配错误。
  • 如果使用了自定义的FSCalendarCell子类,只需要把代码中的FSCalendarCell替换为你的子类即可。
  • 可以根据需求调整圆形边框的颜色、粗细、间距等参数,适配你的APP设计风格。

内容的提问来源于stack exchange,提问作者lakshmi sravya Gajavalli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 22:23:10