Created
February 22, 2024 12:21
-
-
Save kovs705/76ce876596cb94c9ff8e0cb344c9fc0d to your computer and use it in GitHub Desktop.
OTPTextField - modifiable view for receiving and typing OTP codes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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