Engineering
November 08, 2019

Build a Passcode View with Swift

Today we are going to build a Passcode view for our iOS Applications.

img1

The highlights before we are write our code.

- Our Passcode view can “becomeFirstResponder” and “resignFirstResponder” to show and hide virtual keyboard if needed.

\=> Our Passcode nearly same with TextField.

Define our passcode view:

img2

By default, to show keyboard on the screen user should touch in TextField or TextView to edit. We can make our custom view as keyboard input view by override “canBecomeFirstReponder” method and conform to UIKeyInput Protocol

img3

img4

Now our view can show keyboard, you can test it by call passcode.becomeFirstResponder()

img5

img6

To help user easy using our passcode view we can add a tap gesture and call becomFirstReponder() to show keyboard. Now you can easy tap to show keyboard.

img7

Now we are going to build our logic to handle user input. There are 3 methods we need focus:

img8

“InsertText” call when user press any character on keyboard.

“deleteBackward” will call when user press on delete key.

We are define 2 variables to hold user input and determine maximum length of passcode.

img9

The “hasText” variable determined our passcode has any character or not. Simple return it by checking length of code.

img10

Now append or delete our code string if needed.

img11

Greet, our passcode logic finished, the next challenge is map our code to PIN UI when code changed

Add an UIStackView to our Passcode view. Stack will distribute “Dot View” as Pin.

img12

img13

Create our Pin View

img14

Create two more helper methods to create emptyPin and normal pin

img15

Map user input code to Array of Pin views and distribute to stack

img16

The helper method to remove all add Arranged sub view from stack

img17

Call our update stack when code changed

img18

Create ViewController to test our stack:

img19

Make our PasscodeView conform to UITextInputTraints to able to set keyboard to numPad

img20

Result

img21

Add a callback when user finished input.

img22

img23

Full source code at:

https://github.com/viettrungphan/Passcode.git?source=post_page-----a6ddae69f405----------------------

Please notice the project write by Xcode 11 beta. Your can simple copy all Prefix Passxxx and Pin files to your xcode project to test

Work with us

Drop us a message if you need any helps from the Dwarves

Let's build something