How to use Buttons in Swift UI.

Austin Beck
3 min readJun 4, 2021
Photo by Kyle Hanson on Unsplash

When building out your first applications in Swift UI, you are going to quickly encounter the need to utilize buttons in order to achieve different functionality within your program.

When creating a button, it can be a bit daunting to remember the syntax needed and how to format it appropriately as it is quite different than creating actions within UIKit. Today we are going to cover the syntax and application usage for buttons within Swift UI so that you will be prepared to take your application to the next level.

Button Syntax

The syntax for creating a button within your view consists of declaring the button, listing the functions or actions that you want the button to accomplish, and finally creating the text, image, etc for the button and then styling it. This is all accomplished within the same code block and makes for an easy way to add buttons to your program once you learn the syntax.

You can see an example of a button I have created below:

struct MyView: View {
@State var isToggled = false
var body: some View {
VStack {
Button(action: {
isToggled.toggle()
}) {
Text("Press to Toggle").font(.headline)
}
}
}
}

As you can see from the image and code reference above, I have created a button whose action is set to toggle the state variable “isToggled”. When the user selects that button, the value of “isToggled” will change from “false” to “true”. Its as simple as that!

Let’s get down to understanding the actual syntax behind the button from the example above.

Button Syntax

The first line of code in our button is as follows:

Button(action: {
...
})

We are first creating the button object and then within the first curly brackets we are creating the action that the button will accomplish. This can be toggling booleans, setting variable names, calling functions, etc. Any action that you wish to have triggered by the button must fall within the first pair of curly brackets.

The next line of code is below:

}) {
Text("Insert Button Text Here")
}

The second pair of curly brackets allows us to style the actual button. We can place a text object as the button or even an image. All of the stylization options will occur within the second pair of curly brackets.

Conclusion

As you can see from this short article, once you understand how to code a button, it is very easy to start utilizing them within your application to build out the functionality and capabilities of your application.

You may like the following articles:

--

--