Skip to content

SwiftUI: Button

Button allows you to perform an action when triggered.

The method of “triggering” the button may vary. For example, on iOS a button is triggered by tapping it onscreen, whereas on tvOS it’s triggered by pressing “select” on an external remote while the button is focused.

Apple Documentation

In this tutorial, you’ll learn what it takes to build a button with SwiftUI.

Prerequisites

To follow along this tutorial, you’ll need some basic knowledge in:

  • A basic familiarity with Swift.
  • At least Xcode 11 with at least iOS 9.1.

Normal Button

The basic way of building a button is as following.

  • Text is where you set your own text

Button Customization

The following button uses:

  • Padding which creates the rectangle of the button.
  • ForegroundColor which sets the color of the text.
  • background which sets the background color.
  • cornerRadius which sets rounded curve on each corner.

Shadow

  • shadow adds color of the shadow, radius and the position of x and y.

Infinity Corner Radius

infinity will always give you the perfect corner.

Border

.border allows you to create a line around the button. You will still need padding to have a good looking rectangle shape.

Another way of achieving border with the rounded corner is as following:

  • RoundedRectangle which create a corner radius for a rectangle.
  • stroke allows you to adjust the width and color of the border.

Button With Image

Perhaps, showing only text could be a little dull. Why not add some image on it?

  • padding(.horizontal) widens the width of the button. You may disable this if you don’t need it.
  • Image(systemName) allows you to utilize the built in images given by Apple. You may download SF Symbols to better utilize this tool.

In case you would like this image to be of the left. This can be done really easier with a switch of code by moving the image code up one line.

What about just image?

  • renderingMode allows the image to be shown. If you take this line out, you won’t be able to see the image.
  • resizeable allows you to resize the button.
  • aspectRatio allow you to control the content of the image.
  • frame lets you set the width and height.

Where to go From Here

Check out some other tutorials using SwiftUI as well:

Published inSwiftUI

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright © DaddyCoding 2020.