I'm a novice Swift and SwiftUI developer and I have a textfield embedded in a form. I'd like the textfield to return when the user taps anywhere outside of the textfield, and I'm struggling to make this happen. The following toy example illustrates the problem.
import SwiftUI
struct ContentView: View {
@State var name: String = ""
@State var selectedPickerChoice: String = ""
enum FocusedField {
case name, selectedPickerItem
}
@FocusState private var focusedField: FocusedField?
let pickerOptions = ["Option 1", "Option 2", "Option 3"]
var body: some View {
NavigationView {
Form {
HStack {
Text("Name")
Spacer()
TextField("Name", text: $name)
.multilineTextAlignment(.trailing)
.autocapitalization(.words)
.focused($focusedField, equals: .name)
}
/* .onTapGesture {
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
} */
Picker("Picker Choice", selection: $selectedPickerChoice) {
ForEach(pickerOptions, id: \.self) { option in
Text(option)
}
}
.focused($focusedField, equals: .selectedPickerItem)
} // End of Form
/* .onTapGesture {
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
} */
} // End of NavigationView
} // End of body view
} // End of ContentView
In this code example, you can see that I've attempted both .resignFirstResponder and the iOS 15 @FocusState as solutions. Note that the .resignFirstResponder WILL cause the textfield to resign if I use it as a modifier for the form and not the HStack or textfield itself, but when I do this, the picker no longer works.
I am looking to do this without resorting to storyboard and UITextField solutions, and have tried a variety of solutions, including those described here (using Xcode 13.2.1 and 13.2 beta 2) without success.
Any advice is deeply appreciated. Thank you for your time.