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

iOS14与iOS15中SwiftUI LazyVGrid单元格高度不一致问题求助

问题根因

iOS 15 调整了 LazyVGrid 单元格的默认高度计算规则,同列单元格不再默认统一高度,只会适配自身内容的最小高度,导致代码中的VStack没有被撑到最大高度,内部的Spacer自然无法撑开填充空白。

适配解决方案

只需要在原有代码基础上修改两个容器的frame属性即可,不需要调整其他布局逻辑:

  • 给最外层的ZStack添加.frame(maxHeight: .infinity),让单元格可以撑满网格分配的最大高度
  • 给内部承载内容的VStack添加.frame(maxHeight: .infinity, alignment: .top),让VStack撑满整个ZStack的可用空间,内部的Spacer就可以正常撑开,保证所有单元格高度统一

修改后的完整代码参考:

ZStack
{
    Color.white
        .cornerRadius(8)
    
    VStack(alignment: .leading, spacing: 0)
    {
        //  Listing Image…
        
        GeometryReader
        { geom in
            KFImage(self.imageURL)
                .cancelOnDisappear(true)
                .placeholder {
                    Image("product-placeholder")
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .frame(width: geom.size.width, height: geom.size.width)
                }
                .resizable()
                .aspectRatio(contentMode: .fill)
                .frame(width: geom.size.width, height: geom.size.width)
                .cornerRadius(4)
                .clipped()
        }
        .aspectRatio(contentMode: .fit)
        .padding(.bottom, 12)
        
        //  Title…
        
        Text("\(self.title)")
            .font(.custom("Poppins", size: 14.0).weight(.semibold))
            .multilineTextAlignment(.leading)
            .lineLimit(2)
            
        Spacer(minLength: 0)  //  适配后可正常撑开
        
        //  Listing Count…
        
        if let listingCount = self.listingCount
        {
            Text("\(listingCount) listings")
                .font(.custom("Inter", size: 12.0).weight(.medium))
                .foregroundColor(.secondaryText)
                .padding(.vertical, 8)
        }
        
        //  Price…
        
        if let price = self.price
        {
            Text("\(Self.priceFormatter.string(from: price as NSNumber)!)")
                .font(.custom("Inter", size: 14.0).weight(.semibold))
        }
    }
    .padding(12)
    .frame(maxHeight: .infinity, alignment: .top) // 新增适配代码
}
.frame(maxHeight: .infinity) // 新增适配代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 02:24:03