Currently, I am hiding the keyboard when the user taps anywhere. I want to exclude 2 TextField
s tap to avoid the keyboard hide/show effect.
import SwiftUI
struct ContentView: View {
@FocusState var focus:FocusedField?
@State var name = ""
@State var email = ""
@State var phoneNumber = ""
var body: some View {
List {
TextField("Name:",text: $name)
.focused($focus, equals: .name)
.onSubmit {
focus = .email
}
TextField("Email:",text: $email)
.focused($focus, equals: .email)
.onSubmit {
focus = .phone
}
TextField("PhoneNumber:", text: $phoneNumber)
.focused($focus, equals: .phone)
.onSubmit {
if !name.isEmpty && !email.isEmpty && !phoneNumber.isEmpty {
submit()
}
}
}
.onTapGesture {
if (focus != nil) {
hideKeyboard()
}
}
}
private func submit() {
print("submit")
}
enum FocusedField: Hashable {
case name, email, phone
}
}
extension View {
func hideKeyboard() {
print("hideKeyboard")
let resign = #selector(UIResponder.resignFirstResponder)
UIApplication.shared.sendAction(resign, to: nil, from: nil, for: nil)
}
}
I want:
- A stable keyboard for my
TextField
s with no hide and show effects. - Tap anywhere to dismiss/hide the keyboard.
Please see the following effects:
2
Answers
I found the answer.
Use this public struct inside Zstack.
There is a modifier that defines keyboard dismissal available since iOS 16:
You probably want the
immediately
mode.This does not dismiss the keyboard on tap but on scroll which is the typical iOS behaviour.