Skip to content

SwiftUI: Toggle

Toggle is also known as Switch in UIKit with the capability of turning it on or off according to the requirement.

With Toggle, you will have to bind it to a variable in which the variable will be passed into the Toggle’s initializer. From there, you can change the variable’s state from either on or off.

A control that toggles between on and off states.

Apple Documentation

In this tutorial, you’ll learn what it takes to build a toggle in SwiftUI. You’ll learn:

  • How to build a toggle from scratch.
  • How to customize a toggle.

Prerequisites

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

  • A basic familiarity with Swift.
  • At least Xcode 11

Toggle

The first requirement to creating a toggle is to create a variable that holds a state. Here, you will have a state of true.

Now you are half-way done. Insert the state in the initializer and give it a name.

Isn’t it amazing and beautiful how it looks.

Customizing Toggle

It seems like it’s still missing something. I think it’s missing an Image. Now, you will add an image. There will be a slight change in the code.

Depending where you would like your image to be. If you would like your image to be on the left, move the image code above the Text. If you would like the image to be on the right, move the image code below the Text

Where to go From Here

If you feel like you are ready to take on more challenges, feel free to check out some other tutorials that we have created:

Published inSwift

Be First to Comment

Leave a Reply

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

Copyright © DaddyCoding 2020.