Post

Fun SwiftUI tip - conditionally applying background and foreground styles: .background(filled ? AnyShapeStyle(.thickMaterial) : AnyShapeStyle(.clear)) Utilize the AnyShapeStyle wrapper to conditionally apply your style.

What's the problem and why does this work? You'll notice that some view modifiers in SwiftUI like .background or .foreground are expecting you to pass it a type that conforms to the protocol ShapeStyle. So you can't just toggle between Material and Color because while they are two different types

AnyShapeStyle provides us with a common concrete type that we can use when toggling between two different shape styles. Now everyone's happy! You, the compiler, and SwiftUI!

Yea i think this is a trade off. If you are seeing hitches on a rapidly updating view that's using this AnyShapeStyle convenience then I think that would be a great place to optimize. But, otherwise I think it's ok to sprinkle in where necessary. Like most things: IT DEPENDS 😅

0 reposts1 like

No replies yet.