Member-only story

Using the ViewBuilder Attribute to Implement SwiftUI Views in Methods

A technique to separate small view parts implementation quickly and easily!

Gabriel Theodoropoulos
6 min readFeb 25, 2022
Photo by Alan Rodriguez on Unsplash

SwiftUI provides undeniably a funny and innovative way to create user interfaces. We can get great visual results much faster and with less pain comparing to UIKit, despite any lack of features SwiftUI might still has. Usually, we tend to break complex views in smaller components, which, of course, is a good practice; nobody really wants a huge code structure that contains everything in a view, when it’s possible to have smaller chunks or readable and manageable code.

Most of the times we achieve that by creating additional SwiftUI source files, where each one contains the implementation of a different part of the view. Although this is the way to go in the majority of cases, there are circumstances where it seems like a bit of overkill to create a new file just to keep a small portion of the view separated.

Thankfully, there is an alternative, more immediate and quick to implement, which is to implement parts of a view in methods. That is feasible thanks to a specific attribute in SwiftUI, called ViewBuilder, which according to official documentation, it is:

A custom parameter attribute that constructs

--

--

Gabriel Theodoropoulos
Gabriel Theodoropoulos

Written by Gabriel Theodoropoulos

An iOS & macOS app maker writing code in Swift. Author of countless programming tutorials. Content creator. https://serialcoder.dev

No responses yet