Conditional views in SwiftUI
One of the powerful SwiftUI features is custom view modifiers. Let’s see how they can help us to conditionally display the views
Let's take a look at this simple example:
If we would want to hide a subtitle text based on some condition there are few options on how to do this.
The most straightforward is to add a State
variable and if
condition to replace it with the EmptyView
.
It’s simple and easy to read but it becomes a bit messy when there are multiple optional blocks and more complex conditions.
Let’s see how we can use ViewModifier to improve this piece of code. So let’s create one and wrap our condition in it’s body:
Please note that we are wrapping our view into the Group
view to avoid this opaque type error:
“Function declares an opaque return type, but has no return statements in its body from which to infer an underlying type”
Of course, there is a couple of other ways, like wrapping it into AnyView
or using ViewBuilder
property wrapper. It’s up to you what way to choose.
Now we can use our shiny new ViewBuilder to make our view optional:
It already looks a bit nicer. Isn’t it?
But, let’s add an extension to the View
so it’s even easier to use and read.
Here is how our final code will look like:
You can find the final result for the Playground in this Gist on Github.
I hope what I shared did help you!