Swift iOS password toggle — Embed a secure text entry toggle button into a UITextField

Beginner iOS Dev

James Tapping
Level Up Coding
Published in
3 min readJun 14, 2021

--

Image from https://www.cyclonis.com

Like most of my articles — the above is something I’ve had to do for an app of mine. It took a little research so I thought I’d write about it here and save you the time :)

As with a lot of things in iOS development, there are several ways of approaching this. After building a class and an extension to create the button, I found another much simpler way using just an extension of UITextField

Let's get some images for our button — my goto is icons8.com where I found 2 images that were not too bad, an open eye and a closed eye. Download the images as 48px png files. Generally in apps, you'll find that the hidden image is an eye with a diagonal line through it but these will do :) Add these images to your project in the assets folder.

Drop them into all three spaces for the moment, x1 , x2, x3. I changed the name of the open eye to icons8-open-eye-48 just for clarity.

Add a UITextfield to your storyboard. If this is for an existing app, you’ll need an outlet or a reference to the textfield too.

We’ll add the extension now.

Create a new file and call it “UITextField+SecureToggle.swift”

Add the below to the file :

In the code, we are setting the button’s image for two states .selected and .normal then in the togglePasswordView function we toggle the isSelected property of the button and the isSecureEntry property of the textField.

I have changed the alpha of the eye which I feel makes it blend a little better.

Now in the viewController ViewDidLoad add:

password.enablePasswordToggle()

If you gave your uitextfield a different name use that of course.

And that’s pretty much it. Run the project, tap a few characters into the field and test the toggle button.

--

--