SwiftUI圆形进度Gauge尺寸过大,如何调整其大小?
如何缩小SwiftUI圆形Gauge组件的尺寸?
我创建了一个中间带有停止按钮的圆形进度Gauge组件用于进度展示,但该圆形尺寸过大,无法缩小,请问如何调整这个圆形Gauge的大小?
代码:
import SwiftUI struct DownloadProgressGauge: View { var body: some View { Gauge(value: 100, in: 0...200) { Image(systemName: "gauge.medium").resizable().frame(width: 30, height: 30.0) } currentValueLabel: { Image(systemName: "stop.fill").font(.caption).bold() .foregroundStyle(Color.systemBlue) .minimumScaleFactor(0.33) } .gaugeStyle(.accessoryCircularCapacity) .tint(Color.systemBlue) .frame(width: 30, height: 30) } }
当前运行效果:
期望效果:
解决方案
问题根源是.accessoryCircularCapacity系统样式存在固定最小尺寸限制,直接设置frame无法突破该限制,可通过以下两种方式解决:
方法1:使用scaleEffect缩放组件
通过比例缩放整个Gauge,同时调整内部元素尺寸适配:
import SwiftUI struct DownloadProgressGauge: View { var body: some View { Gauge(value: 100, in: 0...200) { Image(systemName: "gauge.medium") } currentValueLabel: { Image(systemName: "stop.fill") .font(.system(size: 12)) .bold() .foregroundStyle(Color.systemBlue) } .gaugeStyle(.accessoryCircularCapacity) .tint(Color.systemBlue) .scaleEffect(0.6) // 按需调整缩放比例 .frame(width: 30, height: 30) } }
方法2:自定义Gauge样式
完全自定义圆形进度样式,摆脱系统样式的尺寸约束,实现精准控制:
import SwiftUI struct CustomCircularGaugeStyle: GaugeStyle { func makeBody(configuration: Configuration) -> some View { let progress = configuration.value / (configuration.maxValue ?? 1) ZStack { // 背景圆环 Circle() .stroke(Color.gray.opacity(0.3), lineWidth: 2) // 进度圆环 Circle() .trim(from: 0, to: progress) .stroke(Color.systemBlue, lineWidth: 2) .rotationEffect(.degrees(-90)) // 中间停止按钮 configuration.currentValueLabel } .frame(width: 30, height: 30) } } struct DownloadProgressGauge: View { var body: some View { Gauge(value: 100, in: 0...200) { EmptyView() } currentValueLabel: { Image(systemName: "stop.fill") .font(.system(size: 12)) .bold() .foregroundStyle(Color.systemBlue) } .gaugeStyle(CustomCircularGaugeStyle()) } }
内容的提问来源于stack exchange,提问作者tech_human
相关产品推荐
相关产品推荐

