I'm making a custom control, specifically a checkbox next to a "label." I want the label
parameter, like many in Apple's built-in controls, to take a view-building closure.
But I can't figure out the correct syntax. I looked at the declaration of Apple's NavigationLink control for clues:
public struct NavigationLink<Label, Destination> : View where Label : View, Destination : View {
/// Creates a navigation link that presents the destination view.
/// - Parameters:
/// - destination: A view for the navigation link to present.
/// - label: A view builder to produce a label describing the `destination`
/// to present.
public init(@ViewBuilder destination: () -> Destination, @ViewBuilder label: () -> Label)
But when I mimic this, the compiler complains about the body() function:
struct CheckboxItem<Label> : View where Label : View
{
let stateCheck: () -> Bool
let label: () -> any View
let boxSize: CGFloat
init(withStateCheck: @escaping () -> Bool, boxSize: CGFloat, @ViewBuilder label: @escaping () -> Label)
{
stateCheck = withStateCheck
self.label = label
self.boxSize = boxSize
}
var body: some View
{
HStack
{ <-- ERROR: "Type 'any View' cannot conform to 'View'"
Image(systemName: stateCheck() ? "checkmark.square" : "square")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: boxSize, height: boxSize)
.foregroundColor(AppStyle.labelColor)
.opacity(0.75)
label()
}
}
}
Also, note that I had to put @escaping before my label parameter, but that's not seen in Apple's.
Any ideas?