Learn different ways to use SwiftUI property wrappers to manage changes to an app’s data values and objects.
This is a companion discussion topic for the original entry at https://www.raywenderlich.com/21522453-swiftui-property-wrappers
Learn different ways to use SwiftUI property wrappers to manage changes to an app’s data values and objects.
This remains an outstanding piece, thank you. Beginning in iOS 15, we can use @FocusedState to set the focus. Consulting some other resources, I created an enum
at the top of the AddThingView
struct:
enum FocusedField {
case shortText, longText
}
I also added an @FocusState
property:
@FocusState private var focusedField: FocusedField?
The body of AddThingView now looks like this:
var body: some View {
VStack {
TextField("TIL", text: $short)
.focused($focusedField, equals: .shortText)
.task { self.focusedField = .shortText }
.disableAutocorrection(true)
.autocapitalization(.allCharacters)
TextField(
"Thing I Learned",
text: $long,
onEditingChanged: { _ in },
onCommit: { saveAndExit() }
)
.focused($focusedField, equals: .longText)
.autocapitalization(.words)
Button("Done") {
saveAndExit()
}
Spacer()
}
.onSubmit {
if focusedField == .shortText {
focusedField = .longText
} else {
focusedField = nil
}
}
.padding()
.textFieldStyle(RoundedBorderTextFieldStyle())
}
This works to get a blinking cursor into the first field when the view loads, but it still doesn’t pop the keyboard. I think that’s a known issue.
— Susannah
FocusedState was to be my question.
Thank you Susannah for your code on this.
Glad to hear it helped!