SwiftUI Button
Chris C
04 May 2021
A Button is a type of control that performs an action when it is triggered. In SwiftUI, a Button typically requires a title text which is the text description of your button, and an action function that will handle an event action when triggered by the user.
Basic Code Sample
When making a basic Button via autocomplete the format is as shown:
Button( "Some Text", action: { //some code } )
The code within the action will be run whenever the button is clicked. Another way this can be formatted is shown below, which is useful if your ‘action’ code is lengthy:
Button(“Some Text”) { // some code }
Styling the Button
Button(“Some Text”) { // some code } .frame(width: 100, height: 100) .font(.title) .foregroundColor.white) .background(Color.blue) .cornerRadius(10)
As shown above, we can add modifiers to the Button like we would to a Text view, such as changing the frame and colors.
We can also use the .buttonStyle modifier to choose from a few predefined styles, such as PlainButtonStyle() which will show the button content in plain black.
Changing the Button Appearance
Button(action: { //code }) { // Some view, example below uses Image Image(systemName: "circle") }
In the code above, we change the structure of how we define the Button so that we can assign the ‘action’ code to a view. Instead of a text label, we can make the button another view such as an Image. In this example, we will have a Circle image that can be pressed to execute the action.
Overall Example
@State var counter = 0 VStack { Text("\(counter)") Button("Increase Count"){ counter += 1 } Button(action: { counter = counter - 1 }) { Image(systemName: "arrow.down") } .buttonStyle(PlainButtonStyle()) }
The code above uses two buttons. The first button with the label “Increase Count” will add one to our counter every time it is pressed. The second button, which is a downwards arrow image, will subtract one from our counter when pressed.