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

iOS 16中如何在SwiftUI的List里缩小View的高度?

在iOS 16的SwiftUI中缩小List行高的解决方案

在iOS 16中,仅设置defaultMinListRowHeight为0无法彻底消除List行的多余空白,可通过以下几种方法解决:

方法一:自定义行内边距+内容高度

给每个列表项添加listRowInsets消除默认内边距,同时通过frame指定内容高度,结合defaultMinListRowHeight环境变量进一步压缩行高:

struct ContentView: View {
    var numbers = 1...10
    var body: some View {
        List {
            ForEach(numbers, id: \.self) { number in
                Text(String(number))
                    .frame(height: 20) // 自定义行内容的高度
                    .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
            }
        }
        .environment(\.defaultMinListRowHeight, 0)
        .padding()
    }
}

方法二:使用listRowHeight环境变量

直接为每个列表项设置listRowHeight环境变量,强制指定行高:

struct ContentView: View {
    var numbers = 1...10
    var body: some View {
        List {
            ForEach(numbers, id: \.self) { number in
                Text(String(number))
                    .environment(\.listRowHeight, 20)
            }
        }
        .padding()
    }
}

方法三:用ScrollView+LazyVStack替代List(完全自定义)

如果不需要List的原生交互(如滑动删除、编辑),可以用ScrollView嵌套LazyVStack实现完全自定义的行高,彻底摆脱List的默认布局限制:

struct ContentView: View {
    var numbers = 1...10
    var body: some View {
        ScrollView {
            LazyVStack(spacing: 0) { // 控制行间距为0
                ForEach(numbers, id: \.self) { number in
                    Text(String(number))
                        .frame(height: 20)
                }
            }
        }
        .padding()
    }
}

注:如果需要保留List的分隔线,可在方法一、二中添加.listRowSeparator(.visible)来手动控制分隔线显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 03:31:51