如何在SwiftUI中创建带白色省略号SFSymbol的圆形按钮?
解决方案
可以通过直接在Button的Label中构建背景,或者自定义ButtonStyle来实现预期效果,以下是两种简洁的实现方式:
方式一:直接构建按钮布局(快速实现)
这种方式无需依赖系统按钮样式,直接分离背景和图标,精准控制颜色和尺寸:
struct ContentView: View { var body: some View { VStack(spacing: 50) { Button(action: {}) { Image(systemName: "ellipsis") .resizable() .scaledToFit() .frame(width: 20) // 控制省略号图标的大小 .foregroundStyle(.white) .frame(width: 40, height: 40) // 按钮整体的圆形尺寸 .background(Color.secondary) .clipShape(Circle()) } } .frame(maxWidth: .infinity, maxHeight: .infinity) .background(Color.black.ignoresSafeArea()) } }
方式二:自定义ButtonStyle(复用场景)
如果需要在多处使用这类按钮,自定义ButtonStyle可以提升复用性,还能添加按压交互反馈:
struct ContentView: View { var body: some View { VStack(spacing: 50) { Button(action: {}) { Image(systemName: "ellipsis") .resizable() .scaledToFit() .frame(width: 20) } .buttonStyle(CircleIconButtonStyle( backgroundColor: .secondary, iconColor: .white, size: 40 )) } .frame(maxWidth: .infinity, maxHeight: .infinity) .background(Color.black.ignoresSafeArea()) } } // 自定义圆形图标按钮样式 struct CircleIconButtonStyle: ButtonStyle { let backgroundColor: Color let iconColor: Color let size: CGFloat func makeBody(configuration: Configuration) -> some View { configuration.label .foregroundStyle(iconColor) .frame(width: size, height: size) .background(backgroundColor) .clipShape(Circle()) .scaleEffect(configuration.isPressed ? 0.95 : 1.0) // 添加按压缩小的反馈 } }
为什么之前的方法不生效?
- 使用
ellipsis.circle.fill图标:这个图标是一个整体矢量图形,Button的tint属性会覆盖整个图标的颜色,foregroundStyle无法单独修改省略号部分,导致无法实现“灰色圆形+白色省略号”的分离效果。 - 使用
borderedProminent样式:系统的borderedProminent自带默认内边距,即使设置了frame和.capsule,按钮的视觉尺寸和点击区域会出现偏差,且需要额外调整才能达到正圆效果,不如直接自定义背景直观。
内容的提问来源于stack exchange,提问作者batman
相关产品推荐
相关产品推荐

