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

SwiftUI实现经典日历日视图:边框样式优化问询

修复SwiftUI日历日视图样式问题

你的代码目前有两个核心问题需要调整:一是日期格式错误,二是样式不符合目标效果,以下是具体的修改方案:

问题分析

  1. 日期格式错误:中间显示日期数字的Text误用了weekday(.twoDigits),这会输出星期几的数字(比如周一=1),而不是当月的日期。
  2. 样式偏差:当前的红色矩形背景、文字颜色搭配不符合目标图的圆形高亮、简洁边框的样式。

修改后的完整代码

import SwiftUI

struct CalendarDayView: View {
    var day = Date()
    
    var body: some View {
        VStack(spacing: 2) {
            // 星期几(短格式)
            Text(day, format: Date.FormatStyle().weekday(.short))
                .font(.caption)
                .foregroundColor(.black)
            
            // 当月日期数字(圆形高亮)
            Text(day, format: Date.FormatStyle().day(.twoDigits))
                .font(.title)
                .fontWeight(.bold)
                .foregroundColor(.white)
                .frame(width: 30, height: 30)
                .background(Color.red)
                .clipShape(Circle())
            
            // 月份+年份(短格式)
            HStack(spacing: 4) {
                Text(day, format: Date.FormatStyle().month(.short))
                Text(day, format: Date.FormatStyle().year(.twoDigits))
            }
            .font(.caption)
            .foregroundColor(.black)
        }
        .frame(width: 60, height: 60)
        .padding(4)
        .background(Color.white)
        .border(Color.gray, width: 1)
    }
}

关键修改点说明

  • 修正日期格式:将日期数字的格式从weekday(.twoDigits)改为day(.twoDigits),正确显示当月的日期数值。
  • 调整高亮样式:给日期数字添加圆形背景(clipShape(Circle())),搭配白色文字+红色背景,匹配目标图的核心视觉效果。
  • 简化文字样式:移除星期、年月部分的红色背景,直接使用黑色文字,让布局更清爽。
  • 添加整体边框:给整个VStack添加灰色边框和白色背景,模拟目标图的卡片式外观。
  • 优化间距:通过spacing参数调整内部元素的间距,让布局更紧凑协调。

内容的提问来源于stack exchange,提问作者Sébastien REMY

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 18:55:33