1

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.

ej5607
  • 309
  • 2
  • 12
  • I tried a number of things, also some of the SO answers, nothing worked :( – the only unsatisfactory solution was to reduce the form height to a minimum and put some clear color underneath it that detects the taps and set focussedField to nil. But that's far from elegant or even practical. – ChrisR Feb 17 '22 at 16:03
  • Hi ChrisR - thank you so much for your time and effort! At least I know that I'm not alone in struggling with this. I'll keep your workaround in mind. – ej5607 Feb 17 '22 at 16:23

0 Answers0