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

如何为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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 20:37:37