SwiftUI List移除多余间距 解决swipeActions高度与行视图不一致问题
问题根源
你将.padding(.bottom)直接加在了绑定swipeActions的视图上,SwiftUI会把这部分padding算入行的整体尺寸,滑动操作的高度会自动匹配整行高度,自然就比你的实际内容视图高出了底部padding的数值。
解决方案
首先移除绑定swipeActions视图上的.padding(.bottom)修饰符,再通过以下两种方案之一实现列表项间距,同时保证滑动操作高度和内容视图完全一致:
方案1:调整listRowInsets实现间距
将原本全0的listRowInsets的底部值调整为你需要的间距大小,这部分间距是列表行的系统预留边距,不属于内容视图范围,不会被计入滑动操作的高度计算:
List(someItems, id: \.self) { item in VStack { TheView() } .swipeActions(allowsFullSwipe: true) { Button { } label: { Label("Hide", systemImage: "eye.slash") } .tint(.accentColor) } .listRowBackground(Color(.red)) // 仅修改底部边距为你需要的间距值,其他方向保持0即可 .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 16, trailing: 0)) .listRowSeparator(.hidden) .cornerRadius(10) .shadow(radius: 2) } .listStyle(PlainListStyle())
方案2:拆分内容视图和间距占位
把滑动操作仅绑定到你的实际内容视图上,列表项的间距用独立的空白占位视图实现,空白视图不绑定滑动操作,自然不会影响其高度:
List(someItems, id: \.self) { item in VStack(spacing: 16) { // spacing数值就是你要的列表项间距 // 仅实际内容视图绑定swipeActions TheView() .cornerRadius(10) .shadow(radius: 2) .swipeActions(allowsFullSwipe: true) { Button { } label: { Label("Hide", systemImage: "eye.slash") } .tint(.accentColor) } // 底部空白占位,不参与滑动操作高度计算 Color.clear.frame(height: 0) } .listRowBackground(Color(.red)) .listRowInsets(EdgeInsets()) .listRowSeparator(.hidden) } .listStyle(PlainListStyle())
如果使用方案2且需要行背景色仅覆盖内容区域,只需把listRowBackground修饰符移到TheView()上即可。
内容的提问来源于stack exchange,提问作者Arturo
相关产品推荐
相关产品推荐

