Wednesday, March 1, 2023

SwiftUI Views Versus Modifiers

John Sundell:

So, regardless of whether we want to change the styles or structure of a view, or introduce a new piece of state, it’s starting to become clear that SwiftUI views and modifiers have the exact same capabilities. But that brings us to the next question — if there are no practical differences between the two approaches, how do we choose between them?

At least to me, it all comes down to the structure of the resulting view hierarchy.

[…]

Looking at the view-based call site above, it’s very clear that our two texts are being wrapped within a container, and it’s also easy to tell which of those two texts will end up being the leading versus trailing view.

That same thing can’t really be said for the modifier-based version this time, though, which really requires us to know that the view that we’re applying the modifier to will end up in the leading slot. Plus, we can’t really tell that those two texts will end up being wrapped in some kind of container at all. It looks more like we’re styling the leading label using the trailing label somehow, which really isn’t the case.

Comments RSS · Twitter · Mastodon

Leave a Comment