Member-only story
A Beginner’s Guide to SwiftUI: Layouts, User Input and Data Handling
Learn about the basics of SwiftUI framework, including how to create and layout views, how to handle user input, and how to work with data.
First introduced in WWDC 2019, SwiftUI helps you build great-looking apps across all Apple platforms with the power of Swift — and surprisingly little code. You can bring even better experiences to everyone, on any Apple device, using just one set of tools and APIs. In this article, we will cover the basics of SwiftUI and how to get started with it.
Let us begin.
Creating and laying out views
In SwiftUI, views are the building blocks of your user interface. You can think of them as the equivalent of UIKit’s UIView
. To create a view, you define a struct that conforms to the View
protocol. Here is an example of a view that displays a simple text label:
struct ContentView: View {
var body: some View {
Text("Hello, World!")
}
}
To lay out views within a container, you can use the VStack
, HStack
, and ZStack
containers. These containers allow you to stack views vertically, horizontally, or on top of each other, respectively. Here is an example of using a VStack
to lay out two text views vertically:
VStack {
Text("First")
Text("Second")
}
You can also use the Spacer
view to push other views to the edges of the container. For example, the following code aligns the two text views at the top and bottom of the container:
VStack {
Spacer()
Text("First")
Spacer()
Text("Second")
Spacer()
}
We also have advanced layout views such as LazyHGrid, LazyVGrid, LazyHStack and many more that I will cover in a separate article for an in-depth look at SwiftUI’s layout system.
Handling user input
SwiftUI provides several ways to handle user input. The most common way is to use @State
variables and bind them to your views. @State
variables are used to store the state of a view, and when they change, the view is automatically updated.