Animated Secure Text Field — SwiftUI

Umut Boz
KoçSistem
Published in
3 min readNov 5, 2022

--

SwiftUI, for your imagination provides an endless environment. In this study, I will present an easy solution for a commonly used approach to login screens. We will develop an animation example that you often use on the SecureField used for the password input field.

You can learn how to watch and show the password using the eye icon. And we will do this with a little animation.

Design

Let’s start with the SecureField design first.

Now, we will add Eye icon to our design. We are going to place the eye icon inside the SecureField. There can use the eye icon from the system icon library. This icon is also known as the visibility eye icon.

Image(systemName: "eye").foregroundColor(.gray).padding()

If we want to place this icon in the SecureField and on the right, we need to place these views under the ZStack.

Animation

Of course, as an interface, this design is our last work, but the codes will be improved. Always think to develop shorter and cleaner code to find the best solution. That’s why you can find our design codes in a very different form in the final.

We want to change the SecureField view when we click on the user’s eye icon. For this, we need to keep state of view object. And this state should be changed when the user clicks on the eye icon.

State

SwiftUI manages the storage of a property that you declare as state. When the value changes, SwiftUI updates the parts of the view hierarchy that depend on the value. Use state as the single source of truth for a given value stored in a view hierarchy.

@State var isSecure: Bool = true

if value of isSecure is True, then view should be SecureField, otherwise TextField should appear.

Animation

When using SwiftUI, you can individually animate changes to views, or to a view’s state, no matter where the effects are. SwiftUI handles all the complexity of these combined, overlapping, and interruptible animations for you.

When we say easeInOut(duration: 0.3) we are actually creating an instance of an Animation structure with its own set of modifiers. So we can add modifiers directly to the animation to add a delay like:

.animation(
.easeInOut(duration: 0.3)
.delay(0.5),
value: isSecure
)

Button (eye icon) must match the state of our program, regardless of what animations. This value is isSecure

Finally

You can find the final output of the study below.

Usage Scenario

VStack(alignment: .center){LoginTextField()AnimatedSecureTextField(text: $password, titleKey: “password”)}.padding(.top, -20)

See you in new studies .. 🤙

--

--