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

SwiftUI如何移除List组件的行间距?

解决SwiftUI List行间距问题

要移除List(plain样式)中forEach生成的行之间的间距,仅用listRowSeparator和listRowInsets不够,还需要添加listRowSpacing(0)来控制行间距,同时检查单元格内部布局,具体操作如下:

关键修改点

  • 给List添加.listRowSpacing(0):直接消除行与行之间的默认垂直间距
  • 确保listRowInsets的top/bottom设为0(你已配置)
  • 检查NotificationViewListCell内部是否存在额外的上下padding,如有则移除

修改后的完整代码

VStack(alignment: .center, spacing: 0) {
    List {
        ForEach(self.viewModel.notifications, id: \.self) { nameDay in
            NotificationViewListCell(day: nameDay)
                .border(.yellow)
                .listRowSeparator(.hidden)
                .listRowInsets(.init(top: 0, leading: 16, bottom: 0, trailing: 0))
        }.onDelete(perform: delete(at:))
    }
    .listStyle(.plain)
    .listRowSpacing(0) // 新增:移除行间距
    .border(.red)
}
.frame(maxWidth: .infinity, maxHeight: CGFloat(self.viewModel.notifications.count * 44))

说明

  • listRowSpacing(0)是plain样式List消除行间距的核心配置,默认plain样式会给行之间添加少量垂直间距,这个 modifier 可以直接覆盖默认值。
  • 如果修改后仍有视觉间距,务必检查NotificationViewListCell的内部布局,比如是否在cell中添加了padding(.vertical)这类会撑开高度的代码,需要将其移除或调整为0。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 03:50:39