SwiftUI:List内嵌ForEach+onMove时如何移除按压白背景保留阴影?
解决方法
要实现按压列表项时仅保留阴影、去掉白色背景,你可以通过清除默认行背景结合自定义交互时的阴影效果来实现,以下是具体方案:
方案一:用手势监听按压状态
先在视图中添加一个状态变量跟踪按压状态,再给行添加手势和动态阴影:
// 先在你的视图结构体里添加这个属性 @GestureState private var isPressed = false // 修改后的List代码 List { ForEach(timerListVM.editTimerList.timerList, id: \.self) { timer in AddTimerRowView(timer: timer) .listRowSeparator(.hidden) .listRowInsets(.init(top: 4, leading: 0, bottom: 8, trailing: 0)) .listRowBackground(Color.clear) // 清除系统默认的白色高亮背景 .contentShape(Rectangle()) // 确保整个行区域都能触发交互 // 常态阴影(可根据需求调整) .shadow(color: .black.opacity(0.2), radius: 4, x: 0, y: 2) // 监听按压手势,动态切换阴影 .gesture( DragGesture(minimumDistance: 0) .updating($isPressed) { _, state, _ in state = true } .onEnded { _ in isPressed = false } ) .shadow(color: isPressed ? .black.opacity(0.3) : .clear, radius: 6, x: 0, y: 4) } .onMove { indexSet, index in timerListVM.editTimerList.timerList.move(fromOffsets: indexSet, toOffset: index) } } .listStyle(.plain) .frame(maxWidth: .infinity)
方案二:自定义ButtonStyle(更简洁)
如果你的行需要响应点击,或者想统一管理交互样式,可以把行包装成Button,自定义按钮样式来控制背景和阴影:
// 先定义一个自定义按钮样式 struct PressableShadowStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { configuration.label .listRowBackground(Color.clear) // 根据按压状态切换阴影参数 .shadow( color: configuration.isPressed ? .black.opacity(0.3) : .black.opacity(0.2), radius: configuration.isPressed ? 6 : 4, x: 0, y: configuration.isPressed ? 4 : 2 ) } } // 在List中使用 List { ForEach(timerListVM.editTimerList.timerList, id: \.self) { timer in Button(action: { // 这里可以添加行的点击逻辑,不需要的话留空即可 }) { AddTimerRowView(timer: timer) .listRowSeparator(.hidden) .listRowInsets(.init(top: 4, leading: 0, bottom: 8, trailing: 0)) } .buttonStyle(PressableShadowStyle()) } .onMove { indexSet, index in timerListVM.editTimerList.timerList.move(fromOffsets: indexSet, toOffset: index) } } .listStyle(.plain) .frame(maxWidth: .infinity)
两种方案的核心都是通过listRowBackground(Color.clear)清除系统默认的白色高亮背景,再通过自定义逻辑添加按压时的阴影效果,完美匹配你的需求。
内容的提问来源于stack exchange,提问作者ludwig95
相关产品推荐
相关产品推荐

