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

SwiftUI中如何根据内容尺寸设置List高度并禁用滚动?

Solution to Disable List Scrolling & Auto-Adjust Height

To achieve your goal of disabling scrolling in a SwiftUI List and making its height automatically fit the content, here's how you can modify your code:

Key Changes Explained:

  • Disable Scrolling: Use .scrollDisabled(true) (iOS 16+) to turn off scrolling without disabling other interactions (like tapping rows). For older iOS versions, you can use .disabled(true)—just note this will make the entire List non-interactive.
  • Auto-Adjust Height: .fixedSize(horizontal: false, vertical: true) forces the List to use its intrinsic content height instead of expanding to fill available vertical space.
  • Clean Up Styling: .listStyle(.plain) removes default List padding and grouped styling that adds unnecessary space. Adding .listRowInsets(EdgeInsets()) to each row eliminates default left/right padding for a tighter layout.

Modified Code:

var body: some View { 
    List{
        ForEach(testData){ data in
            VStack(alignment: .leading){
                HStack{
                    Image(data.name)
                        .resizable()
                        .frame(width: 50, height: 50, alignment: .leading)
                    VStack(alignment: .leading){
                        Text(data.name)
                            .bold()
                        Text(data.bio)
                            .font(.subheadline)
                    }
                }
            }
            .listRowInsets(EdgeInsets()) // Remove default row padding
            .padding(.vertical, 4) // Optional: Add small vertical spacing between rows
        }
    }
    .scrollDisabled(true) // Disable scrolling
    .listStyle(.plain) // Simplify List styling to avoid extra space
    .fixedSize(horizontal: false, vertical: true) // Fit List to content height
    .offset(y:-60)
    .padding(8)
}

Notes:

  • The optional .padding(.vertical, 4) adds a small gap between rows for better readability—feel free to adjust or remove it based on your design needs.
  • If you need to keep the List's interactive elements (like taps) on older iOS versions, you'll need a workaround using UITableViewRepresentable, but the above solution works for most modern use cases.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:00:11