Skip to content

Hengyu/PasscodeField

Repository files navigation

PasscodeField

PasscodeField provides a passcode field written in SwiftUI.

  1. Digit length is customizable;
  2. Digit box style is customizable;
  3. Support for hide/unhide digits.

Table of contents

Requirements

  • iOS 13.0+, tvOS 14.0+, macOS 11.0+
  • SwiftUI

Usage

In the Swift file you want to use, just import the package and then:

import PasscodeField

// ... some code ...

PasscodeField { digits, action in
    if candidatePasscodes.contains(digits.concat) {
        withAnimation {
            isPresentingPasscode = false
        }
        action(true)
    } else {
        withAnimation {
            isShowingAlert = true
        }
        action(false)
    }
} label: {
    VStack(alignment: .center, spacing: 8) {
        Text("Security Number")
        .font(.title)
        .foregroundColor(Color(.label))

        Text("4 digits")
        .font(.footnote)
        .foregroundColor(Color(.secondaryLabel))
    }
}
.alert(
    "Wrong Passcode",
    isPresented: $isShowingAlert,
    confirmationText: "Retry",
    confirmationAction: {
        isShowingAlert = false
    },
    cancellationText: "Quit",
    cancellationAction: {
        isShowingAlert = false
        dismissAction()
    }
)

Installation

Swift Package Manager

PasscodeField could be installed via Swift Package Manager. Open Xcode and go to File -> Add Packages..., search https://github.com/hengyu/PasscodeField.git, and add the package as one of your project's dependency.

Manual

  1. Download code from GitHub;
  2. Drag & drop the Sources folder into your project.

Core Ideas

To provide the system input keyboard to user when they interacting the PasscodeField, we use a system text field as the receiver while making it visually invisible. When user is about to input digits, we first make the text field as the first responder. At this time, the system keyboard will show. Then we listen to the input event, when any input arrives, we validate the input and then update the state of the PasscodeField (e.g., set a gray background on the digit box to indicate user they have added one digit). Also, we listen to the text deletion event, and update the PasscodeField correspondingly.

License

PasscodeField is available under the MIT License.

About

A SwiftUI implementation on passcode view

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages