I am having trouble getting the keyboard to dismiss. When nil it should dismiss but it’s not working so I added the dismiss but that’s also not working. The keyboard flashes but stays. Any suggestions on what I’m missing here. I’m testing on ios17 both in the simulator and on phone and get the same problem:
Here is the code I’m trying:
import SwiftUI
struct ContentView: View {
@Environment(.colorScheme) var colorScheme
@FocusState private var focusedField: Field?
@State private var lastname: String = ""
enum Field: Hashable {
case lastName
}
var body: some View {
VStack {
HStack {
TextField("Last name", text: $lastname)
.disableAutocorrection(true)
.foregroundColor(Color.primary)
.autocapitalization(.words)
.textContentType(.familyName)
.focused($focusedField, equals: .lastName)
.submitLabel(.done)
.onSubmit {
focusedField = nil
dismissKeyboard()
}
.onTapGesture {
focusedField = .lastName
}
Spacer()
}
.frame(height: 40)
.overlay(
Rectangle() // This creates the underline effect
.frame(height: 0.75)
.foregroundColor(colorScheme == .dark ? .white : .black)
.padding(.top, 30)
)
.padding()
}
}
private func dismissKeyboard() {
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}