如何移除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状态下的残留样式,按以下步骤修改:
- 移除多余圆角设置:删除原代码中Button内部HStack和Button本身的
.cornerRadius(1),这是导致圆角的直接原因。 - 自定义ButtonStyle控制hover状态:默认
PlainButtonStyle仍可能保留hover时的圆角,自定义样式强制消除圆角并适配布局。 - 保留布局适配设置:维持
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
相关产品推荐
相关产品推荐

