SwiftUI Menu中如何实现横向排列的圆形按钮选项?
要实现横向排列的圆形按钮菜单,核心是通过自定义MenuStyle覆盖系统默认的纵向布局,同时调整按钮样式为圆形。以下是具体实现方案:
1. 自定义横向菜单样式
创建遵循MenuStyle协议的结构体,在makeBody方法中重新定义菜单弹出内容的布局与样式:
struct HorizontalCircleMenuStyle: MenuStyle { func makeBody(configuration: Configuration) -> some View { Menu(configuration) .menuContent { HStack(spacing: 16) { ForEach(configuration.children) { child in child .labelStyle(.iconOnly) // 仅显示图标,隐藏文字 .frame(width: 44, height: 44) .background(Color(.systemGray5)) .clipShape(Circle()) } } .padding(12) .background(Color(.systemBackground)) .cornerRadius(16) .shadow(radius: 8) } } } // 扩展MenuStyle,简化调用 extension MenuStyle where Self == HorizontalCircleMenuStyle { static var horizontalCircle: HorizontalCircleMenuStyle { .init() } }
2. 修改ContentView应用自定义样式
给原有Menu添加自定义样式,同时确保按钮仅显示图标:
import SwiftUI func testing() { print("Hello") } struct ContentView: View { var body: some View { VStack { Menu { Button(action: testing) { Label("Button 1", systemImage: "pencil.tip.crop.circle.badge.plus") } Button(action: testing) { Label("Button 2", systemImage: "doc") } Button(action: testing) { Label("Button 3", systemImage: "trash") } } label: { Label("", systemImage: "ellipsis.circle") .font(.title) } .menuStyle(.horizontalCircle) // 应用自定义样式 } .padding() } }
关键说明
- 直接在Menu内容中使用HStack无效,是因为系统默认MenuStyle强制纵向布局,自定义MenuStyle可以完全重构弹出菜单的布局逻辑。
- 通过
.labelStyle(.iconOnly)隐藏按钮文字,配合固定宽高、圆形背景实现圆形按钮效果。 - 给弹出菜单添加背景、圆角和阴影,还原你在SwiftUI Playgrounds中看到的样式。
内容的提问来源于stack exchange,提问作者adammenges
相关产品推荐
相关产品推荐

