What Is State in SwiftUI and How Do We Use It?

An explanation of one of the most important concepts in SwiftUI

Mayur Rathod
Better Programming

--

As we all know, Apple has released SwiftUI for building user interfaces across all Apple platforms using the power of Swift. Before I show you what we’ll be building in this piece, let me explain one of the most important concepts in SwiftUI development: state.

What is State?

The state represents the data associated with the view. It can be represented by a primitive type like Boolean, String, Int, or a complex object like a view model. Say you’re a user and you interact in some way — you click the button, which triggers an action, that changes the value of the @State variable. Then it automatically updates the user interface.

How does it automatically update the user interface?

When using the View, the Content View is conforming to a View protocol and we have to write the Body property. So whenever we change the value of the @State variable it updates the View and the body property is evaluated again — so the View re-renders again.

Enough of the theory. Let’s see how to use the @State variable in XCode and find out what we’ll be building.

Step 1: How to Create SwiftUI Project

In XCode go to File → New → Project → Single View App → Next → Select User Interface → SwiftUI → Next → Select Project location where you want to save this project → Done

Step 2: ContentView.swift

Default SwiftUI(ContentView) file comes up with the following code:

import SwiftUIstruct ContentView: View {
var body: some View {
Text(”Hello World!”)
}
}
struct ContentView_Previews: PreviewProvider {
static
var previews: some View {
ContentView()
}
}

On the right-hand side, you can see the preview of the UI. If you can’t see the preview go to Adjust Editor Option on the top right and select Canvas or press option+command+enter. Then make sure that Canvas is showing the UI preview.

Step 3: Creating a User Interface

Define the vertical stack inside the ContentView body. This will contain Text and the Change Name button.

Code:

VStack {Text(”Hello World!”)Button(“Change Name”)
{
//Button action goes
here
}
}

For the final output we want to customize the text font size, button font size, background color, text color, and we want to make the edges of the button circular.

First, we modify the button code so we can access the Button’s Text Property. After modification, the code will look something like this:

VStack{
Text(”Hello World!”)
Button(action: {
//Button action goes here
}){
Text(“Change Name”)
}
}

Now let’s take a look at the properties we’ll use to achieve our desired output.

We can change the font size using the property .font().

Text(name)
.font(.largeTitle) // Font type

We can change the background color using the property .background(Color.COLOR_NAME)

Text(“Change Name”) // Button Text
.background(Color.orange) // Button Background Color

To change the text color we can use property .foregroundColor(Color.COLOR_NAME)

Text(“Change Name”) // Button Text
.foregroundColor(Color.white) // Button text color

To make the edges circular we can use the property .cornerRadius(CORNER_RADIUS_VALUE)

Text(“Change Name”) // Button Text
.cornerRadius(10.0) // Button corner radius property

If we apply all of the properties above to the text and button appropriately our code will look like this:

//Vertical Stack
VStack {
//Text or label of the name
Text(name)
.font(.largeTitle) // Font type
.padding() // Padding to the name text
Button(action : { //Button action goes here }){
//Button Text Properties
Text(“Change Name”) // Button Text
.fontWeight(.heavy) // Button Text Weight
.padding() // Padding to the button
.background(Color.orange) // Button Background Color
.foregroundColor(Color.white) // Button text color
.cornerRadius(10.0) // Button corner radius property
}
}

Output:

Now our UI is ready, let’s see how to use the @State variable.

Step 04: How to Use @State Variable

Now we declare the state variable. To declare a state variable we have to use the @State keyword before declaring the variable. Check the line below for a better understanding of how to declare state variable:

@State var name = “Mayur”

We want to change the state variable value whenever the user clicks the button. To do this we need to change the value of the variable inside the Button ACTION block. To access the state variable inside the button action method we need to define the self.STATE_VARIABLE_NAME so it looks something like this:

self.name = “Rathod”

When the user clicks the button it changes the state variable value. When the state variable value is changed it renders the view again and changes the displayed text value.

Congratulations You Have Successfully Achieved Your Output.

The whole code looks like this:

//
// ContentView.swift
// State-Demo
//
// Created by Mayur on 14/10/19.
// Copyright © 2019 Mayur Rathod. All rights reserved.
//

import SwiftUI

struct ContentView: View {

@State var name = "Mayur"

var body: some View {
//Vertical Stack
VStack {

//Text or label of the name
Text(name)
.font(.largeTitle) // Font type


Button(action : {
/*
- When user clicks on the button this block will be executed
- When user click on the button View will rendered again since we are changing or mutating the @State variabl value
*/
self.name = "Rathod"
}){
//Button Text Properties
Text("Chnage Name") // Button Text
.fontWeight(.heavy) // Button Text Weight
.padding() // Padding to the button
.background(Color.orange) // Button Background Color
.foregroundColor(Color.white) // Button text color
.cornerRadius(10.0) // Button corner radius property
}
}
}
}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

Resources

--

--