I am trying to create an OTP page for my app but I don't know how to make the next textfield focus after I input a single digit in the first text field.
I created 6 text field for each digit of OTP. The next text field should be the first responder once I key in one digit from the first text field and so forth untill all 6 digits are complete.
I'm not sure how to do that in Swift UI. So far I manage to create 6 lines only as seen in the screenshot. The expected is only one digit should be per line. So the next text field should be focus once I input a single integer.
I tried other post like the use of @FocusState but it says unknown attribute.
I also tried the custom text field How to move to next TextField in SwiftUI? but I cannot seem to make it work.
import SwiftUI
struct ContentView: View {
@State private var OTP1 = ""
@State private var OTP2 = ""
@State private var OTP3 = ""
@State private var OTP4 = ""
@State private var OTP5 = ""
@State private var OTP6 = ""
var body: some View {
VStack {
HStack(spacing: 16) {
VStack {
TextField("", text: $OTP1)
Line()
.stroke(style: StrokeStyle(lineWidth: 1))
.frame(width: 41, height: 1)
}
VStack {
TextField("", text: $OTP2)
Line()
.stroke(style: StrokeStyle(lineWidth: 1))
.frame(width: 41, height: 1)
}
VStack {
TextField("", text: $OTP3)
Line()
.stroke(style: StrokeStyle(lineWidth: 1))
.frame(width: 41, height: 1)
}
VStack {
TextField("", text: $OTP4)
Line()
.stroke(style: StrokeStyle(lineWidth: 1))
.frame(width: 41, height: 1)
}
VStack {
TextField("", text: $OTP5)
Line()
.stroke(style: StrokeStyle(lineWidth: 1))
.frame(width: 41, height: 1)
}
VStack {
TextField("", text: $OTP6)
Line()
.stroke(style: StrokeStyle(lineWidth: 1))
.frame(width: 41, height: 1)
}
}
}
}
}
struct Line: Shape {
func path(in rect: CGRect) -> Path {
var path = Path()
path.move(to: CGPoint(x: 0, y: 0))
path.addLine(to: CGPoint(x: rect.width, y: 0))
return path
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.previewLayout(.fixed(width: 560, height: 50))
}
}