Better Programming

Advice for programmers.

Follow publication

Member-only story

How to Build Better Password Entry in SwiftUI

Add a show/hide password button to your password text field

David Piper
Better Programming
Published in
5 min readMar 1, 2020
Photo by Shane Avery on Unsplash

Many big apps — like YouTube, Twitter, and Amazon — allow their users to switch between a secured text field and a normal text field whenever a password needs to be entered. This is a good user experience because it’ll be very frustrating for your users to need multiple tries to log in just because they have a complex password and made a spelling mistake.

In this piece, we’ll explore how to recreate this function in SwiftUI. First, we’ll see how to use a SecureField to obscure the entered text. Next, we’ll add the button to toggle between this kind of text field and a normal TextField showing the content as plain text.

The two images below show the final result of this tutorial: In the left one, the password is obscured so it’s not visible, but in the right one, a user can see what was entered. The button to toggle the visibility will show a closed eye icon when the password isn’t readable and an opened eye icon when it is readable.

Adding a button to show and hide the password in a TextField. Left: Password hidden. Right: Password shown. Icons made by Freepik from www.flaticon.com.

Implementation

First, let’s start by adding a new SwiftUI View. You can add a new file via File → New → File… or by pressing Cmd+N.

Creating a new SwiftUI View — adding a new file

Next, you need to choose the SwiftUI View template. You can find it in the section called “User Interface” or by using the filter text field.

Creating a new SwiftUI View — choosing the SwiftUI View template

This will create a new view, which will show a simple “Hello, World!” in a label. Beginning with this template, we can start to design and implement our UI. First, replace the content of the default struct with the following:

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

David Piper
David Piper

Written by David Piper

Working as an iOS and Android dev.

Responses (3)

Write a response