Last active
December 14, 2022 04:04
-
-
Save gewill/7f81742fc4e1f7ae23b2f4ffc0fee300 to your computer and use it in GitHub Desktop.
SwiftUI TextField focus, thanks to https://github.com/Asperi-Demo/4SwiftUI/blob/master/PlayOn_iOS/PlayOn_iOS/Findings/TestNextTextFieldFocus.swift
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 | |
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