Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Term Entry] SwiftUI Concept: Buttons #5809

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
183 changes: 183 additions & 0 deletions content/swiftui/concepts/buttons/buttons.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
---
Title: 'Buttons'
Description: 'Button is a view that triggers an action when tapped.'
Subjects:
- 'Mobile Development'
- 'iOS'
Tags:
- 'SwiftUI'
- 'Buttons'
CatalogContent:
- 'learn-swift'
- 'paths/build-ios-apps-with-swiftui'
---

**`Button`** is a view in SwiftUI that triggers an action when tapped. It is one of the essential components for creating interactive apps, allowing users to perform actions.

## Creating Buttons

Buttons are created by specifying an action (code to execute when the button is tapped) and a label (the content of the button that is displayed to users). For example:

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Buttons in SwiftUI can use multiple types of views as labels, not just Text. This could be explicitly mentioned for beginners beforehand, but it should probably be covered in a Syntax header, and then usage should be explained in examples.

Buttons in SwiftUI can use any SwiftUI view as a label, not just `Text`. This allows for highly customizable and complex button content, such as combining icons, shapes, or even animations.

```swift
Button(action: {
print("Button tapped!")
}) {
Text("Tap Me")
}
```

## Customizing Buttons

Buttons can be styled and customized using SwiftUI modifiers to change their appearance. For example, you can modify fonts, colors, backgrounds, and more.

```swift
Button(action: {
print("Custom button tapped!")
}) {
Text("Click Me")
.font(.title)
.foregroundColor(.white)
.padding()
.background(Color.blue)
.cornerRadius(10)
}
```
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should include images and output on clicking the button in each case for good understanding.


## Button Styles

SwiftUI provides several built-in button styles that can change the appearance of buttons globally:

- **`DefaultButtonStyle`**: The standard button appearance.
PragatiVerma18 marked this conversation as resolved.
Show resolved Hide resolved
- **`PlainButtonStyle`**: Removes visual styling, leaving only the label content.
- **`BorderedButtonStyle`**: Adds a border to the button (available in iOS 15+).
- **`BorderlessButtonStyle`**: Removes borders, often used in toolbars or lists.
PragatiVerma18 marked this conversation as resolved.
Show resolved Hide resolved

You can apply these styles using the `.buttonStyle()` modifier:

```swift
Button("Styled Button") {
print("Styled button tapped!")
}
.buttonStyle(BorderedButtonStyle())
```

## Example

Here’s an example of a `VStack` containing buttons with different styles and labels:

```swift
import SwiftUI

struct ButtonExampleView: View {
var body: some View {
VStack(spacing: 20) {
Button("Simple Button") {
print("Simple button tapped!")
}

Button(action: {
print("Custom button tapped!")
}) {
Text("Custom Button")
.font(.headline)
.foregroundColor(.white)
.padding()
.background(Color.green)
.cornerRadius(8)
}

Button(action: {
print("Image button tapped!")
}) {
HStack {
Image(systemName: "star.fill")
.foregroundColor(.yellow)
Text("Image Button")
.font(.body)
}
}
}
.padding()
}
}
```

Explanation:

- The **first button** is a simple text button.
- The **second button** uses custom styling with a green background and rounded corners.
- The **third button** combines an image and text within an `HStack`.

## Basic Button

A simple button in SwiftUI is created using the `Button` view. You can pass a closure (action) to the button that will be executed when the button is tapped:

```swift
Button("Tap Me") {
print("Button tapped!")
}
```
Comment on lines +111 to +119
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The "Basic Button" section largely overlaps with the "Creating Buttons" section. Consolidating these or adding new value to the second section will improve the flow.


## Buttons with Custom Content

You can also create buttons with custom content, such as text, images, or other SwiftUI views. The content inside the button can be customized as needed:

```swift
Button(action: {
print("Custom button tapped!")
}) {
HStack {
Image(systemName: "star.fill")
.foregroundColor(.yellow)
Text("Star Button")
.font(.title)
}
}
```

In this example:

The button displays an image and text.
Comment on lines +138 to +140
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add an image example here.

The HStack is used to arrange the image and text horizontally.
PragatiVerma18 marked this conversation as resolved.
Show resolved Hide resolved

## Button Actions

You can define any action inside the button’s closure. For instance, navigating to a new view, changing a state, or interacting with a model can be done in the action block:

```swift
Button("Navigate") {
// Navigate to a new view
// Navigation logic goes here
}
```

## Button Modifiers

SwiftUI offers various modifiers to style and configure buttons:

- `.font()` to change the font of the button label.
- `.foregroundColor()` to set the text color.
- `.background()` to set the button's background color.
- `.cornerRadius()` to round the button's corners.

```swift
Button("Styled Button") {
print("Styled button tapped!")
}
.font(.headline)
.foregroundColor(.white)
.padding()
.background(Color.blue)
.cornerRadius(10)
```

## Disabled Buttons

You can disable buttons by using the `.disabled()` modifier. Disabled buttons are non-interactive and will appear grayed out:
PragatiVerma18 marked this conversation as resolved.
Show resolved Hide resolved

```swift
Button("Disabled Button") {
// Action here
}
.disabled(true)
```
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add ButtonRole Information (iOS 15+). The new ButtonRole API in iOS 15+ allows buttons to have semantic roles like "destructive" or "cancel". Mentioning this improves completeness of this doc.

Starting in iOS 15, you can specify a `ButtonRole` (e.g., `.destructive` or `.cancel`) to provide semantic meaning to the button:
```swift
Button("Delete", role: .destructive) {
    print("Delete action")
}