I am creating a Form
using SwiftUI
. Within my Form
, I have a DatePicker
, TextField
, and a SegmentedPickerStyle
.
My TextField
is using a .decimalPad
and I'm trying to find the best way to dismiss the keyboard when finished typing.
I have tried adding a .onTapGesture
but it prevents me from using any of my Pickers. When I tap on them nothing happens.
Here is what I am trying to do:
struct ContentView: View {
@State var date = Date()
@State var price = ""
@State private var tipPercentage = 2
let tipPercentages = [10, 15, 20, 25, 0]
var body: some View {
NavigationView {
Form {
Section {
DatePicker(selection: $date, displayedComponents: .date) {
Text("Date").bold().foregroundColor(Color.init(red: 100.0/255.0, green: 208.0/255.0, blue: 100.0/255.0))
}
HStack {
Text("Price"))
Spacer()
TextField("required", text: $price).multilineTextAlignment(.trailing).keyboardType(.decimalPad)
}
}
Section(header: Text("How much tip do you want to leave?")) {
Picker("Tip percentage", selection: $tipPercentage) {
ForEach(0 ..< tipPercentages.count) {
Text("\(self.tipPercentages[$0])%")
}
}
.pickerStyle(SegmentedPickerStyle())
}
}
.onTapGesture {
let keyWindow = UIApplication.shared.connectedScenes
.filter({$0.activationState == .foregroundActive})
.map({$0 as? UIWindowScene})
.compactMap({$0})
.first?.windows
.filter({$0.isKeyWindow}).first
keyWindow!.endEditing(true)
}
}
}
}
remove your .onTapGesture and add this to the Form:
.gesture(DragGesture().onChanged{_ in UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)})