SwiftUI实现经典日历日视图:边框样式优化问询
修复SwiftUI日历日视图样式问题
你的代码目前有两个核心问题需要调整:一是日期格式错误,二是样式不符合目标效果,以下是具体的修改方案:
问题分析
- 日期格式错误:中间显示日期数字的
Text误用了weekday(.twoDigits),这会输出星期几的数字(比如周一=1),而不是当月的日期。 - 样式偏差:当前的红色矩形背景、文字颜色搭配不符合目标图的圆形高亮、简洁边框的样式。
修改后的完整代码
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
相关产品推荐
相关产品推荐

