Is there a way to conditionally blur a view in SwiftUI?
For example for VStack:
VStack {
//contents
}.blur(radius: 20)
Would blur the view. However, I’d like to blur it based on a condition.
I could use an if statement but that would mean writing the view twice in code like so:
if(shouldBlur)
{
VStack {
//contents
}.blur(radius: 20)
}
else
{
VStack {
//contents
}
}
Is this the only way to achieve the desired outcome?
3
Answers
There are a few different methods you could use. Methods 2 and 3 involve some duplication, but you can abstract that out of your direct view hierarchy.
We can just use
0
(no blur), likeYou can just store Views in variables, like so:
And then use the same View twice in your body, like so:
And if your View needs dynamic properties you can use functions that return AnyView, like so: