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

如何移除List中Button的圆角?解决hover时布局适配问题

解决List中Button圆角及Hover布局适配问题

问题描述

需要移除List组件内Button的圆角,当前按钮处于hover状态时无法适配List布局。

原代码

Section(header: Text("Schema Items")) {
    ForEach(cards[cardIndex].indentedSchemaItems.indices, id: \.self) { index in
        Button(action: {
           
        }) {
            HStack {
               
            }
            .padding(.vertical, 8)
            .frame(height: 88)
            .cornerRadius(1)
        }
        .buttonStyle(PlainButtonStyle()) // Remove button style to make it look like a regular view
        .listRowInsets(EdgeInsets())
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .frame(height: 88)
        .cornerRadius(1)
    }
}.environment(\.defaultMinListRowHeight, 0)

解决方案

问题根源在于重复设置的cornerRadius以及默认ButtonStyle在hover状态下的残留样式,按以下步骤修改:

  1. 移除多余圆角设置:删除原代码中Button内部HStack和Button本身的.cornerRadius(1),这是导致圆角的直接原因。
  2. 自定义ButtonStyle控制hover状态:默认PlainButtonStyle仍可能保留hover时的圆角,自定义样式强制消除圆角并适配布局。
  3. 保留布局适配设置:维持listRowInsets(EdgeInsets())和frame配置,确保按钮填满List行。

修改后的代码:

Section(header: Text("Schema Items")) {
    ForEach(cards[cardIndex].indentedSchemaItems.indices, id: \.self) { index in
        Button(action: {
            // 你的点击逻辑
        }) {
            HStack {
                // 你的内容
            }
            .padding(.vertical, 8)
            .frame(height: 88)
        }
        .buttonStyle(CustomPlainButtonStyle())
        .listRowInsets(EdgeInsets())
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .frame(height: 88)
    }
}.environment(\.defaultMinListRowHeight, 0)

// 自定义无圆角的Button样式,控制hover/按下状态
struct CustomPlainButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .background(configuration.isPressed ? Color.gray.opacity(0.1) : Color.clear)
            .cornerRadius(0) // 强制设置圆角为0
    }
}

说明

  • 自定义样式CustomPlainButtonStyle直接接管按钮的状态渲染,明确设置圆角为0,彻底消除hover时的圆角问题。
  • 移除重复的圆角设置后,按钮布局会完全贴合List行,hover时不会出现偏移。

内容的提问来源于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:55:08