import SwiftUI
struct Stone: View {
@FocusState var focusedField: Int?
@State var index: Int
@State private var text: String = ""
var body: some View {
TextField("", text: $text)
.focused($focusedField, equals: index)
.textFieldStyle(.roundedBorder)
.onChange(of: text) { newValue in
if newValue.count >= 1 {
setFocus(index: index)
text = String(newValue.last!)
}
}
}
func setFocus(index: Int) {
/// Default to the first box when focus is not set or the user reaches the last box
if focusedField == nil || focusedField == 9 {
focusedField = 0
} else {
/// Another safety check for the index
if index == 9 {
focusedField = 0
} else {
focusedField = index + 1
}
}
}
}
struct TemplateUI: View {
@State private var username = ""
@State private var numberText = ""
@FocusState private var focusedField: Int?
var body: some View {
HStack(spacing: 3) {
ForEach(0..<10, id: \.self) { index in
Stone(focusedField: _focusedField, index: index)
.border(.black, width: 1)
}
}
.padding(.horizontal)
}![](https://velog.velcdn.com/images/kikidy12/post/c0929916-f31e-475a-8d15-f47b839331d4/image.png)
}
struct TemplateUI_Previews: PreviewProvider {
static var previews: some View {
TemplateUI()
}
}