If you are trying to follow along, please know that SwiftUI requires XCode 11 and macOS 10.15, all of which is in developer beta right now.
This post will walk you through how to make a basic iOS app that counts how many times a button is tapped.
1. Create a new project
The first step is to launch XCode and create a new single page iOS application. When creating the iOS app, make sure Use SwiftUI is checked.
2. Create a variable and make the app output that variable
Next, we need to create a @State variable so that it can dynamically change when a button is tapped. Inside the ContentView struct, add @State var totalClicked: Int = 0 and change the string inside Text() to "\(totalClicked)").
Now, we need to embed the text in a verticle stack to place the button below the Text(). To do this Command + Click on the 0 in the live preview and choose Embed in VStack.
By embedding in a VStack, the struct now looks like this:
structContentView:View{@StatevartotalClicked:Int=0varbody:someView{VStack{// this was addedText("Hello World")}}}
4. Add a Button with an action
It's time to add a button. A way to do this is by first adding a Text(). Add the following to your struct:
// more stuff aboveVStack{Text("\(totalClicked)")Text("Increment Total) // <- This is what to add
}
// more stuff below
Now, let's use the live preview to embed the Text() in a button. Command + Click on Increment Total in Live Preview and select Embed in Button.
We need to adjust the Button code that is now in ContentView.swift. Adjust button to look like the following:
Currently, the button and the text have no space between each other and the size of the total is quite small. In SwiftUI, you can adjust this pretty easily.
First, let's adjust the font size of the total by adding .font(.title) after the Text call.
Text("\(totalClicked").font(.title)
Next, we will add some space between the button and the text. To do this, we need to add Spacer() between the text and the button.
If you liked the tutorial and project, please consider being a sponsor of this project and others like it by clicking the sponser button at the top of the repo, or by going directly to my Patreon.