Skip to content

Instantly share code, notes, and snippets.

@kovs705
Created February 22, 2024 12:21
Show Gist options
  • Save kovs705/76ce876596cb94c9ff8e0cb344c9fc0d to your computer and use it in GitHub Desktop.
Save kovs705/76ce876596cb94c9ff8e0cb344c9fc0d to your computer and use it in GitHub Desktop.
OTPTextField - modifiable view for receiving and typing OTP codes
import SwiftUI
import Combine
struct OTPTextFieldView: View {
private enum FocusField: Hashable {
case field
}
@State var text = ""
@FocusState private var focusedField: FocusField?
init() {
UITextField.appearance().clearButtonMode = .never
UITextField.appearance().tintColor = UIColor.clear
}
private var backgroundTextField: some View {
return TextField("", text: $text)
.onChange(of: text) { newValue in
if newValue.count > 6 {
text = String(newValue.prefix(6))
}
}
.frame(width: 0, height: 0, alignment: .center)
.font(Font.system(size: 0))
.accentColor(.blue)
.foregroundColor(.blue)
.multilineTextAlignment(.center)
.keyboardType(.numberPad)
.focused($focusedField, equals: .field)
.task {
DispatchQueue.main.async
{
self.focusedField = .field
}
}
.padding()
}
public var body: some View {
ZStack(alignment: .center) {
backgroundTextField
HStack {
ForEach(0..<6) { index in
ZStack {
Text(getPin(at: index))
.font(Font.system(size: 27))
.fontWeight(.semibold)
.foregroundColor(Color.blue)
RoundedRectangle(cornerRadius: 10, style: .continuous)
.frame(width: 50, height: 50)
.foregroundColor(Color.gray.opacity(0.3))
.padding(.trailing, 5)
.padding(.leading, 5)
}
}
}
}
}
func getPin(at index: Int) -> String {
guard self.text.count > index else {
return ""
}
let stringIndex = self.text.index(self.text.startIndex, offsetBy: index)
return String(self.text[stringIndex])
}
}
#Preview {
OTPTextFieldView()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment