I would like to be able to pass the GaugeStyle
for a Gauge
as a parameter to my own SwiftUI view, however I can't seem to get this to work with the compiler. When I try the below code I get an error, Type 'any View' cannot conform to 'View'
.
import SwiftUI
struct MyGauge: View {
let min = 0.0
let max = 10.0
let current = 5.0
let style: any GaugeStyle = .accessoryCircular
var body: some View {
Gauge(value: current, in: min...max) {
Text("Gauge")
} currentValueLabel: {
Text("\(current)")
} minimumValueLabel: {
Text("\(min)")
} maximumValueLabel: {
Text("\(max)")
}
.gaugeStyle(style)
}
}
(Code is simplified for brevity.)
What's the correct way to allow a GaugeStyle
to be passed around?
CodePudding user response:
SwiftUI requires concrete types for most areas of a View
especially wrappers and view modifiers.
The any
keyword is "existential"
@available(iOS 16.0, *)
struct MyGauge<G>: View where G : GaugeStyle{
let min = 0.0
let max = 10.0
let current = 5.0
let style: G
init(style: G = .accessoryCircular){
self.style = style
}
var body: some View {
Gauge(value: current, in: min...max) {
Text("Gauge")
} currentValueLabel: {
Text("\(current)")
} minimumValueLabel: {
Text("\(min)")
} maximumValueLabel: {
Text("\(max)")
}
.gaugeStyle(style)
}
}
@available(iOS 16.0, *)
struct MyGauge_Previews: PreviewProvider {
static var previews: some View {
MyGauge()
MyGauge(style: .accessoryLinear)
}
}