SPB Git

Repository Public MIT

glass-otp-field.md 3.0 KB

# GlassOTPField

Identifier glass-otp-field
Module SPGlassForms
Kind content-component — one system TextField under a row of opaque boxes
Platforms iOS 26, iPadOS 26, macOS 26
Example Examples/Gallery/Forms/GlassOTPFieldExample.swift

# Minimal usage

swift
@State private var code = ""

GlassOTPField(code: $code) { code in
    verify(code)
}

# Variants

Variant Use
length: 4 … 8 Number of digits. Six by default.
hasError: true Outlines the boxes in the destructive colour after a rejected code.
label: Accessibility label when "Verification code" is not the right name (a PIN, for example).

# Parameters

Parameter Type Default Meaning
code Binding<String> — Digits entered so far, ASCII only.
length Int 6 Number of digits.
label LocalizedStringKey? "Verification code" Accessibility label.
hasError Bool false Error outline.
onComplete @MainActor (String) -> Void { _ in } Called each time the code becomes complete.

# States

Empty, partially filled (the next box is outlined while the field has focus), complete (onComplete fires), error, disabled. Clearing the binding (code = "") resets the field.

# Advanced example

swift
GlassOTPField(code: $code, length: 6, hasError: model.codeRejected) { entered in
    Task { await model.verify(entered) }
}
.onChange(of: code) { _, _ in model.codeRejected = false }
.disabled(model.isVerifying)

Input is cleaned by the pure GlassOTPSanitizer.sanitize(_:length:):

swift
GlassOTPSanitizer.sanitize("Your code is 482 913.", length: 6)   // "482913"
GlassOTPSanitizer.sanitize("١٢٣٤٥٦", length: 6)                  // "123456"

# Accessibility

  • There is one text field, so VoiceOver meets one element: its label and the value "3 of 6 digits entered". The boxes are hidden from assistive technologies and the digits are not read one box at a time by GlassKit.
  • The field uses the one-time-code content type, so the system can offer the code received by message, and the number pad on iOS.
  • Pasting a whole code works as in any text field: long-press or Command-V; separators and letters are dropped.
  • Boxes share the available width, their height follows Dynamic Type, and the digits shrink rather than clip.
  • Digits are always laid out left to right, including in right-to-left languages.

# Limits

  • Digits only; alphanumeric codes are not supported.
  • The code lives only in the host's binding. The component stores, logs and copies nothing; clear the binding when you are done.
  • The text field is drawn transparent over the boxes, so the system caret and selection highlight are not visible; the outlined box shows the position instead.
  • Digits of other scripts are converted to ASCII; symbols that only look like numbers (fractions, Roman numerals, circled digits) are dropped.
  • AutoFill from Messages, the paste menu and VoiceOver output need a device and were not exercised here.
Files main
Menu

Theme