Member-only story
How to Build Better Password Entry in SwiftUI
Add a show/hide password button to your password text field

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.


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.

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.

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: