How to Use Buttons in SwiftUI?

In the tutorial, you'll learn to use Buttons in SwiftUI with only a few lines of swift code.

Share:

Oct 26, 2023 420 Words

Read Time: 2 Minutes

A screenshot of a simple button implementation in SwiftUI

Introduction

Welcome to the world of SwiftUI, where creating interactive user interfaces is a breeze. Buttons are a fundamental part of any app, and SwiftUI makes it easy to add and customize them. In this blog post, we’ll explore how to use buttons in SwiftUI, and as an example, we’ll create a button that changes the color of a text when clicked.

You’ll see how simple and intuitive it is to work with buttons in SwiftUI, even if you’re just starting out.

I’ll first present the code snippet and then will attempt explain it.

Code Snippet

import SwiftUI

struct ContentView: View {
    @State private var textColor: Color = .black // Initial text color

    // List of predefined colors
    let colorOptions: [Color] = [.red, .green, .blue, .purple, .orange]

    var body: some View {
        VStack {
            Text("Click button to change color")
                .font(.title)
                .foregroundColor(textColor) // Use the textColor state variable
            
            Button("Click Me") {
                // Change the text color to a randomly selected color
                textColor = getRandomColor()
            }
            .foregroundColor(.white)
            .background(Color.blue)
            .padding()
        }
    }

    // Function to get a randomly selected color from the list
    func getRandomColor() -> Color {
        let randomIndex = Int.random(in: 0..<colorOptions.count)
        return colorOptions[randomIndex]
    }
}

In the code snippet above, we’ve created a simple SwiftUI view that includes a button. This button, when clicked, changes the color of a text to a randomly selected color from a predefined list.

📲 Copy and paste this code inside your ContentView.swift in Xcode to modify and understand it.

Explanation

  1. Setting Up the View: We start by creating a SwiftUI view named ContentView. Inside this view, we use the @State property wrapper to manage the textColor. Initially, the text color is set to black.

  2. Defining Color Options: We define an array called colorOptions that contains several predefined colors that we can choose from.

  3. Creating the Button: We add a button with the label “Click Me.” Inside the button’s action closure, we call the getRandomColor() function to change the text color to a randomly selected color from our list.

  4. Random Color Selection: The getRandomColor() function generates a random index within the range of the colorOptions array and returns the corresponding color.

Output

Below is a simple gif showing what the above code snippet does as iOS application inside the Xcode’s iOS simulator.

A small gif of a simple swiftui button in action

Conclusion

In this blog post, we’ve explored the basics of using buttons in SwiftUI, and you’ve seen how to create a button that changes the color of a text when clicked.

👋 – @TnvMadhav

References

Find more posts from following topics

accurate-requests
api-development
api-testing
api-testing-tools
array
automated-testing
bad-habits
base64-decoder
base64-encoder
binding
blog
blogging
bulma-css
bulma.io
button-swiftui
chatgpt
chrome
clipboard
code
code-block
code-snippet
codecoverage
comparison
compile
configuring-debugger-for-django-in-vs-code
configuring-launch.json-for-python-debugger
copy
copy-to-clipboard
copy-to-clipboard-neovim
css
current-date
current-time
current-timestamp
debugger-setup-in-visual-studio-code
debugging-django-app-in-visual-studio-code
debugging-python-code-in-visual-studio-code
debugging-python-programs-with-visual-studio-code
debugging-python-with-virtual-environment-in-vs-code
developer-productivity
developers
development-workflow
dom
dynamic-sitemap-in-nextjs
engineering-dashboard
flowcharts
git
git-diff
github
global-keyboard-shorcut
global-shortcut
go
go-hugo
go-programming
go-test
go-to-line
go-tool
golang
golang-development
good-habits
gorilla-websocket
gpt
gpt-3.5
gpt-4
gpt-4-api
guide
gumroad
habits
habits-tracker-notion-template
hamburger-menu
hotkeys
html
hugo
ide
image
image-sharing
image-tool-for-ios
imagerenderer
include-timestamp
integrated-development-environment
ios
ios-16
ios16
javascript
keyboard-shortcut
linux
macos
map
markdown
markdown-code
mental-programming
menu
menubarextra
mergesort
mermaid-syntax
mistake-tracker-notion
mobile-view
modifier
navbar
navigationlink
navigationstack
neovim
next.js
nextjs
nextjs-markdown
nextjs-sitemap
nextjs-sitemaps
nice-shot
nice-shot-pro
notion
notion-api
notion-api-python
notion-budget
notion-budget-template
notion-budget-tracker
notion-bug-report-tracker
notion-dashboard
notion-expense-manager
notion-habits
notion-habits-dashboard
notion-habits-template
notion-habits-tracker
notion-habits-tracker-template
notion-issue-tracker
notion-mistake-tracker
notion-product
notion-product-dashboard
notion-product-roadmap
notion-product-roadmap-dashboard
notion-tasks
notion-tasks-dashboard
notion-tasks-template
notion-tasks-tracker
notion-template
notionworkspaces
openai
osx
personal-ifttt-framework
photospicker
photospickeritem
phpickerfilter
postman-capabilities
postman-request
pre-request-script
product-roadmap-notion-template
product-roadmap-template
productivity
programming
python
python-api
python-debugger-tutorial-for-vs-code
python-debugging-mode-in-vs-code
python-notion-api
python3
real-time-communication
rehype
remark
request-data
running-debugger-in-visual-studio-code
running-django-app-in-debugging-mode
running-program-in-debugging-mode-in-vs-code
running-python-code-in-debugging-mode
safari
screenshot-app-for-ios
screenshot-app-ios
screenshot-ios
screenshot-tool-for-ios
set-current-timestamp
setting-up-debugger-in-vs-code-for-python
share-extension
sharelink
sharepreview
sharesheet
simple-websocket-server
sitemap
slice
slider
sorting
space-complexity
step-by-step-guide
stocks-profits-tracker
stocks-profits-tracker-template
stocks-tracker
struct
sustained-vigilance
swift
swiftui
swiftui-button
swiftui-button-action
swiftui-button-style
table-of-contents
tasks-tracker-notion-template
test
testing
textfield-swiftui
til
tim-sort
time-complexity
timeliness
timestamp-integration
timsort
transferable
triggers-and-actions
tutorial
unittest
us-stocks
usa-stocks
useful-ios-features
using-breakpoints-in-python-debugger
using-virtual-environment-with-python-debugger
vanilla-javascript
variable
vim
visual-mode
visual-studio-code
vs-code
vscode
vscode-go-to-line
web-sockets-in-go
websocket-client
websocket-programming
websocket-server
xcode