Adding a dismiss button to numberpad swiftUI

Viewed 178

Although I found a couple tutorials for this online however this is as far as I could figure out.

HStack{
    TextField("Placeholder", text: $text)
        .keyboardType(.numberPad)
    Button(action: {
        self.hideKeyboard()
        }, label: {
        Image(systemName: "keyboard.chevron.compact.down")
        })
}
#if canImport(UIKit)
extension View {
    func hideKeyboard() {
        UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
    }
}
#endif

Eventhough this works, I would prefer if I could put the button in a toolbar onto of the keypad which I can't figure out how to do.

1 Answers

if your main aim is to dismiss key board you can do the following

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }

if you want to create a tool bar and manage your view so that when a textfield is clicked it doesn't occupy the space of textfield there is a very elegant cocoapod for that you just have to install it .its called IQKeyboardManager. You just have to write one single line in didFinishLaunchingWithOptions method in AppDelegates .

IQKeyboardManager.shared.enable = true

Thats it now everything will be managed by it.

Related