Understand SwiftUI Views & View Hierarchies
Written by Team Kodeco
At the heart of an iOS app developed with SwiftUI lies a collection of views, which are essentially the building blocks that make up your user interface. Here, we’ll go over some basics of how SwiftUI views work.
What’s a View?
In SwiftUI, View
is a property wrapper that provides a mechanism for creating and modifying views in response to changes in state or data. A view can be a button, a text label or anything that represents the user interface. Views are typically aggregated together to form a hierarchy that makes up a screen.
Views can be nested to create a hierarchy that determines the structure of the user interface. The root view is the entry point of the application and typically holds the top of the hierarchy.
Each view has a parent and can have children. Next, you’ll look at how to build a simple hierarchy with a parent and two children.
Building a View Hierarchy
First, add this image to your Assets.xcassets:
Then, replace your ContentView
with the following:
struct ContentView: View {
var body: some View {
VStack {
Image("Kodeco")
Text("Welcome to the Kodeco SwiftUI cookbook!")
}
}
}
The preview should then show the following:
In the code above, we define a ContentView
struct which conforms to the View
protocol. Inside the body
property, we define a VStack
view, which is a view that arranges its subviews in a vertical stack. In this example, the VStack
has two subviews (a Text
view and an Image
view), vertically stacked one on top of the other.
Notice that the body
property uses a closure syntax, where you define the content of the view hierarchy. The return value of body
must be a single view, but that view can contain many subviews, each of which can contain more subviews, and so on.
Aiming for a flat hierarchy can improve simplicity and maintainability. For complex view hierarchies, consider using different VStack
, HStack
or ZStack
instances to logically group and visually separate parts of the user interface. (Note: You might be wondering about a limit on the number of subviews; we’ll touch on this topic in a later section.)
For more details, see the “Views & Modifiers in SwiftUI” section in this cookbook.