Skip to content

Instantly share code, notes, and snippets.

@gewill
Last active December 14, 2022 04:04
Show Gist options
  • Save gewill/7f81742fc4e1f7ae23b2f4ffc0fee300 to your computer and use it in GitHub Desktop.
Save gewill/7f81742fc4e1f7ae23b2f4ffc0fee300 to your computer and use it in GitHub Desktop.
import SwiftUI
struct TestNextTextFieldFocus: View {
@State var inputsValues: [String] = (0..<30).map { i in
"test \(i) TextField axis is \(i % 2 == 0 ? ".vertical" : ".horizontal")"
}
@FocusState var focusedInput: Int?
var body: some View {
ScrollViewReader { proxy in
ScrollView {
LazyVStack {
ForEach(0..<inputsValues.count, id: \.self) { i in
TextField("Value", text: $inputsValues[i], axis: i % 2 == 0 ? .vertical : .horizontal)
.focused($focusedInput, equals: i)
.submitLabel(.return)
.id(i)
.onSubmit {
print("submit \(i)")
// update state here !!
if (i + 1) < inputsValues.count {
focusedInput = i + 1
} else {
focusedInput = nil
}
}
}
}
.onChange(of: focusedInput) {
print("onChange focusedInput:\(String(describing: focusedInput))")
// react on state change here !!
proxy.scrollTo($0, anchor: .top)
}
}
.toolbar {
ToolbarItemGroup(placement: .keyboard) {
Spacer()
Button {
focusedInput = nil
} label: {
Text("Done")
}
}
}
}
}
}
struct TestNextTextFieldFocus_Previews: PreviewProvider {
static var previews: some View {
TestNextTextFieldFocus()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment