Build a Passcode View with Swift
Today we are going to build a Passcode view for our iOS Applications.
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:
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
Now our view can show keyboard, you can test it by call passcode.becomeFirstResponder()
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.
Now we are going to build our logic to handle user input. There are 3 methods we need focus:
“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.
The “hasText” variable determined our passcode has any character or not. Simple return it by checking length of code.
Now append or delete our code string if needed.
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.
Create our Pin View
Create two more helper methods to create emptyPin and normal pin
Map user input code to Array of Pin views and distribute to stack
The helper method to remove all add Arranged sub view from stack
Call our update stack when code changed
Create ViewController to test our stack:
Make our PasscodeView conform to UITextInputTraints to able to set keyboard to numPad
Add a callback when user finished input.
Full source code at:
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 DwarvesLet's build something