如何为SwiftUI列表中的整个单元格添加悬停效果?
解决SwiftUI列表单元格悬停效果覆盖整个区域的问题
你的当前代码中,悬停效果仅作用于单元格内的文本区域,而非整个单元格范围,问题出在容器视图未填充整个单元格空间。
问题示意图:
只需给HStack添加横向填充,并确保交互区域覆盖整个单元格即可解决:
Section(header: Text("Schema Items")) { ForEach(cards[cardIndex].indentedSchemaItems.indices, id: \.self) { index in HStack { Text("text") } .frame(maxWidth: .infinity) // 让容器占满单元格整个宽度 .contentShape(Rectangle()) // 将悬停/点击区域扩展到整个容器范围 .hoverEffect(.highlight) } }
如果需要自定义单元格内边距,可添加listRowInsets来调整:
Section(header: Text("Schema Items")) { ForEach(cards[cardIndex].indentedSchemaItems.indices, id: \.self) { index in HStack { Text("text") } .frame(maxWidth: .infinity) .listRowInsets(EdgeInsets(top: 8, leading: 16, bottom: 8, trailing: 16)) .contentShape(Rectangle()) .hoverEffect(.highlight) } }
核心逻辑:
frame(maxWidth: .infinity)强制容器横向铺满单元格可用空间contentShape(Rectangle())把交互区域(包括悬停)从文本内容扩展到整个容器的frame
内容的提问来源于stack exchange,提问作者János
相关产品推荐
相关产品推荐


