Adding Buttons

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Buttons are an easy way to provide interactivity to your app. These are views that run code when tapped. The good thing about buttons is that the button itself is just another view. For example, you can use an image or text. This is part of the flexibility of buttons.

Buttons in code look like the following:

Button {
    // Swift code
} label: {
    // View
}

As you can see, the Button looks like a little different than other views. It requires a few curly braces. These are areas where you can provide lots of code.

Here is a completed button:

Button {
    print("Hello world")
} label: {
    Text("Tap me")
}

In this case, this produces a text button. Once the user taps the button, the message is printed to the console. Notice the Text view is being used for the label. You can provide an image or compose an entirely new view with accompanying modifiers.

See forum comments
Download course materials from Github
Previous: Demo: Modifying Views Next: Demo: Adding Buttons