Learn how to create and use Buttons in SwiftUI. Style the button with text and images, add border around it. Perform actions when button is pressed and update SwiftUI view accordingly.
SwiftUI Button is similar to UIButton from UIKit when it comes to behavior however you define it in a different way by specifying an action closure and a label view.
The code to create a basic button looks like this:
Button(action: {
print("Button action")
}) {
Text("Button label")
}
The action closure is executed when you press the button which has a Text label defined in the trailing closure. In fact, the label of the button is a View which can contain images or other views.
Create a button with image and text as a label (grouped into HStack):
Button(action: {
print("Button action")
}) {
HStack {
Image(systemName: "bookmark.fill")
Text("Bookmark")
}
}
Add a rounded border to a button with image and text:
Button(action: {
print("Button action")
}) {
HStack {
Image(systemName: "bookmark.fill")
Text("Bookmark")
}.padding(10.0)
.overlay(
RoundedRectangle(cornerRadius: 10.0)
.stroke(lineWidth: 2.0)
)
}
Adding the border around HStack requires using the .overlay() modifier with layered RoundedRectangle shape on top of it.
Add a shadow around the button’s border:
Button(action: {
print("Button action")
}) {
Text("Button label")
.padding(10.0)
.overlay(
RoundedRectangle(cornerRadius: 10.0)
.stroke(lineWidth: 2.0)
.shadow(color: .blue, radius: 10.0)
)
}
Experiment with the .shadow() modifier and apply it to the entire Button view – note that the shadow is applied to both the border and text of the button at the same time.
In order to modify a state of a view with a button action, update a @State variable of the view which controls what gets displayed on the screen. For example, let’s control a counter value with our button and display the current counter value:
struct ContentView: View {
@State var counter = 0
var body: some View {
VStack {
Text("Counter value: \(self.counter)")
.foregroundColor(.blue)
Button(action: {
self.counter += 1
}) {
HStack {
Image(systemName: "plus")
Text("Increment")
}.padding(10.0)
.overlay(
RoundedRectangle(cornerRadius: 10.0)
.stroke(lineWidth: 2.0)
)
}
Spacer()
}
}
}
Take a look at Apple’s official SwiftUI Button documentation.
Related tutorials: