This is my code:
struct GameView : View {
@State
private var clicked1 : Bool = false
var body: some View {
HStack {
VStack {
Image("shape0")
.overlay(clicked1 ?
RoundedRectangle(cornerRadius:10)
.stroke(Color.yellow, lineWidth: 7) : pass()
)
.onTapGesure {
print("Image is clicked")
}
}
}
}
}
But some errors happen around pass().
I want to do nothing when variable clicked1 is false.
How can I fix it?
.overlay expects some View type as a parameter.
If you want to use a ternary operator, it has to return the same type. For a "do nothing" view, use EmptyView(), but since it has to be the same type, one way to do this would be by wrapping each conditional view with AnyView:
Image("shape0")
.overlay(clicked1
? AnyView(RoundedRectangle(cornerRadius:10)
.stroke(Color.yellow, lineWidth: 7))
: AnyView(EmptyView())
)
EDIT:
Actually - Optional<Wrapped: View> also conforms to View, so this is a better approach than above - i.e. just return the view you want or nil:
Image("shape0")
.overlay(clicked1 ? RoundedRectangle(cornerRadius:10)
.stroke(Color.yellow, lineWidth: 7) : nil)
Another approach would be to use computed property which returns a conditional view:
var body: some View {
Image("shape0")
.overlay(overlayView)
}
@ViewBuilder
var overlayView: some View {
if clicked1 {
RoundedRectangle(cornerRadius:10)
.stroke(Color.yellow, lineWidth: 7)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With