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

SwiftUI Grid实现固定尺寸正方形单元格的问题咨询

实现自定义尺寸的正方形单元格Grid解决方案

问题根源分析

  • Cell1:直接固定了10x10的frame,导致尺寸无法自定义;
  • Cell2:使用fixedSize()会强制视图保留自身理想尺寸(比如你的Path是50x50),但Grid的布局系统仍按初始小尺寸分配单元格空间,导致内容溢出出现黑条;移除fixedSize()后,Grid会拉伸单元格适配容器,破坏正方形比例。

方案1:固定自定义尺寸的正方形单元格

直接给单元格设置明确的宽高为自定义值,让Grid根据这个尺寸完成布局,既保证正方形比例,又支持自定义大小:

struct CustomSizeSquareGrid: View {
    // 可自定义的单元格尺寸,传入50就是50x50的正方形
    let cellSize: CGFloat
    // 示例行列数,可按需调整
    let gridRows: Int = 4
    let gridColumns: Int = 4
    
    var body: some View {
        Grid(horizontalSpacing: 0, verticalSpacing: 0) {
            ForEach(0..<gridRows, id: \.self) { _ in
                GridRow {
                    ForEach(0..<gridColumns, id: \.self) { _ in
                        SquareCell(size: cellSize)
                    }
                }
            }
        }
    }
}

struct SquareCell: View {
    let size: CGFloat
    
    var body: some View {
        // 替换为你的自定义内容(比如Path)
        Path { path in
            path.addRect(CGRect(x: 0, y: 0, width: size, height: size))
        }
        .stroke(Color.black)
        .frame(width: size, height: size) // 强制单元格保持正方形尺寸
        .background(Color.yellow.opacity(0.3))
    }
}

使用时直接传入目标尺寸:

CustomSizeSquareGrid(cellSize: 50)

方案2:自适应父容器的正方形单元格

如果需要单元格自动填满父容器且保持正方形(比如尽可能大的正方形),用GeometryReader计算可用空间:

struct AdaptiveSquareGrid: View {
    let gridRows: Int = 4
    let gridColumns: Int = 4
    // 单元格间距,可自定义
    let spacing: CGFloat = 2
    
    var body: some View {
        GeometryReader { geo in
            // 取父容器宽高的最小值,保证Grid整体为正方形
            let containerSize = min(geo.size.width, geo.size.height)
            // 计算单个单元格尺寸:扣除总间距后平分
            let totalSpacing = spacing * CGFloat(max(gridRows, gridColumns) - 1)
            let cellSize = (containerSize - totalSpacing) / CGFloat(max(gridRows, gridColumns))
            
            Grid(horizontalSpacing: spacing, verticalSpacing: spacing) {
                ForEach(0..<gridRows, id: \.self) { _ in
                    GridRow {
                        ForEach(0..<gridColumns, id: \.self) { _ in
                            SquareCell(size: cellSize)
                        }
                    }
                }
            }
            .frame(width: containerSize, height: containerSize)
        }
    }
}

关键注意点

  • 避免使用fixedSize():它会脱离Grid的布局约束,导致内容溢出;
  • 明确设置单元格的frame(width:height:):这是保证正方形比例的核心,让Grid能正确感知单元格的尺寸需求;
  • 带间距的场景:计算单元格尺寸时要把总间距从可用空间中扣除,避免Grid超出父容器范围。

内容的提问来源于stack exchange,提问作者g i i k

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 19:13:27