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

SwiftUI中List组件后出现大量空白,如何消除?

SwiftUI List 短列表后空白问题解决办法

方法一:让List自适应内容高度

给List添加fixedSize(horizontal: false, vertical: true)修饰符,强制List仅占用实际内容所需的垂直空间,这样后续的Text就能紧贴列表最后一项。

修改后的代码:

struct ContentView: View {
    var body: some View {
        VStack {
            List {
                Section("Test"){
                    Text("Hello")
                    Text("Hello again")
                }
            }
            .listStyle(.plain)
            .fixedSize(horizontal: false, vertical: true) // 关键代码
            
            Text("Hello once more")
            Spacer()
        }
    }
}

方法二:手动模拟List样式(自定义高度)

如果fixedSize在复杂场景下有局限,用ScrollView+LazyVStack还原List的Section和条目样式,完全控制内容高度:

struct ContentView: View {
    var body: some View {
        VStack {
            ScrollView {
                LazyVStack(spacing: 0) {
                    // 模拟Section标题
                    Text("Test")
                        .font(.headline)
                        .padding(.horizontal, 16)
                        .padding(.vertical, 8)
                        .background(Color(.systemGroupedBackground))
                    
                    // 模拟列表项
                    Text("Hello")
                        .padding(.horizontal, 16)
                        .padding(.vertical, 12)
                        .background(Color(.systemBackground))
                        .border(Color(.separator), edge: .bottom)
                    
                    Text("Hello again")
                        .padding(.horizontal, 16)
                        .padding(.vertical, 12)
                        .background(Color(.systemBackground))
                }
            }
            .background(Color(.systemGroupedBackground))
            
            Text("Hello once more")
            Spacer()
        }
    }
}

// 扩展View,方便添加单一边框
extension View {
    func border(_ color: Color, edge: Edge, lineWidth: CGFloat = 1) -> some View {
        overlay(
            Rectangle()
                .fill(color)
                .frame(height: lineWidth)
                .alignmentGuide(edge) { $0[.bottom] }
        )
    }
}

第一种方法最简洁,完美保留List原生交互和样式;第二种方法适合需要高度自定义布局的场景,彻底避免List的默认填充行为。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 02:35:59