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

SwiftUI CS193p Set游戏开发:如何阻止GridItem自动扩张?

问题根因

你的核心问题出在两个地方:

  1. AspectVGrid中计算好单元格宽度后,使用了.adaptive类型的GridItem,系统会自动调整列数和实际单元格宽度,导致你预设的宽高比失效,卡牌实际高度小于预期
  2. CardView内部有冗余的宽高比限制,图形高度计算没有考虑内边距,导致3个图形的总高度超过卡牌可用空间

修复步骤

1. 修改AspectVGrid的GridItem配置

将adaptiveGridItem方法中的GridItem类型从.adaptive改为.fixed,直接使用你计算好的宽度,保证每个单元格宽度严格一致:

private func adaptiveGridItem(width: CGFloat) -> GridItem {
    var gridItem = GridItem(.fixed(width))
    gridItem.spacing = 0
    return gridItem
}

2. 重构CardView的布局逻辑

移除冗余的GeometryReader和重复的宽高比限制,让内部图形自动适配卡牌可用空间:

struct CardView: View {
    let card: Model.Card
    
    var body: some View {
        ZStack{
            let shape = RoundedRectangle(cornerRadius: 10)
            if !card.isMatched {
                shape.fill().foregroundColor(.white)
                shape.strokeBorder(lineWidth: 4).foregroundColor(card.isSelected ? .red : .blue)
            }
            VStack(spacing: 6) {
                ForEach(0..<card.numberOfShapes, id: \.self) { index in
                    cardShape()
                        .scaledToFit()
                }
            }
            .padding(12)
            .foregroundColor(setColor())
        }
        .aspectRatio(6/8, contentMode: .fit)
    }
}

说明

修改后所有卡牌会严格按照你设置的宽高比等比例缩放,新增/移除卡牌时自适应逻辑依然生效,内部1/2/3个图形都会自动适配卡牌内部空间,不会出现溢出或者被裁剪的问题,所有卡牌尺寸完全一致。

内容的提问来源于stack exchange,提问作者Amanda

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 04:15:03