SwiftUI中用Rectangle绘制平行线条实现日历图标
使用Rectangle实现日期CardView顶部的双红线日历样式
完全可以用Rectangle()实现这个效果,不需要用Path()。核心问题是你之前把线条和文本放在了同级VStack中,导致线条位置偏离;正确的做法是把日期文本和两条红线放在ZStack里,通过对齐和偏移定位红线到方形框的顶部中心。
修改后的代码实现
把原来的Text部分替换成下面的ZStack结构,就能实现目标效果:
ZStack(alignment: .topCenter) { // 原有日期文本+方形边框 Text(FormatDisplay.yyyymmdd_day0(inputDate: workout.date)) .padding(2) .background(RoundedRectangle(cornerRadius: 2).stroke(Color(UIColor.label).opacity(0.8), lineWidth: 2)) .font(.footnote) .minimumScaleFactor(0.5) // 顶部平行红线 HStack(spacing: 4) { Rectangle() .fill(Color.red) .frame(width: 6, height: 2) Rectangle() .fill(Color.red) .frame(width: 6, height: 2) } .offset(y: -7) // 可根据字体、padding大小微调此值,让红线刚好贴在方形框顶部 }
关键逻辑说明
ZStack(alignment: .topCenter)确保红线对齐到容器顶部中心HStack(spacing: 4)控制两条红线的间距,调整spacing值可改变线之间的距离offset(y: -7)将红线向上偏移,使其脱离文本区域,刚好落在方形边框顶部
替换后完整的VStack代码如下:
VStack { ZStack(alignment: .topCenter) { Text(FormatDisplay.yyyymmdd_day0(inputDate: workout.date)) .padding(2) .background(RoundedRectangle(cornerRadius: 2).stroke(Color(UIColor.label).opacity(0.8), lineWidth: 2)) .font(.footnote) .minimumScaleFactor(0.5) HStack(spacing: 4) { Rectangle() .fill(Color.red) .frame(width: 6, height: 2) Rectangle() .fill(Color.red) .frame(width: 6, height: 2) } .offset(y: -7) } if workout.icuId != "" { Image("intervalsLogo") .resizable() .aspectRatio(contentMode: .fit) .frame(width: 20, height: 20, alignment: .top) .clipShape(Circle()) } if workout.priorityCompliance > 0 { RingView(compliancePct: workout.priorityCompliance, lineWidth: 2, primaryColor: Color.orange, secondaryColor: Color.orange, size: .tiny) .frame(width: 20, height: 20) .font(.caption) } Spacer() }
内容的提问来源于stack exchange,提问作者app4g
相关产品推荐
相关产品推荐

