Hide Keyboard in app

Hi All,

I have just started to learn swiftui and just messing around.

I have created a form got a couple of text boxes in it with decimal keyboard and also a picker in the form

The problem I have is that when you click in the text box you can’t make the keypad go, is there a way to put a done button on the keypad?

@Seesor Welcome to the community!

What I typically do is something like this, although there are other solutions.

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
           hideKeyboard()
       }

    
    func hideKeyboard() {
        yourTextField.resignFirstResponder()
    }

You can also do this when the user taps return on the keyboard:

//Add the delegate to the class
UITextFieldDelegate

//In viewDidLoad add the following
//Delegate need to connect return key on keyboard
        addField.delegate = self



func textFieldShouldReturn(_ taskFiled: UITextField) -> Bool {
        self.view.endEditing(true)
        
        if yourTextField!.isEmpty {
            //Empty so close
            taskFiled.text = ""
            
            return true
        }
        
        //Do whatever the field does here.
        return true
    }

Blessings,
—Mark

Thanks Mark I will give this a try

Hello,
I am trying to add code that will dismiss the numeric keyboard but I am having trouble. I am new to coding so forgive my ignorance. I searched here on the threads and came across this thread. I used the above code but it is not working for me. I am sure it is due to my error somewhere.

I am placing the code in the view controller where my UITextFields are located and at the end of the code. Is that the correct view controller? If so, where in the code should it be placed? Below is the code that I am using.

// Dismiss Keyboard
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
hideKeyboard()
}

     func hideKeyboard() {
         efficiency.resignFirstResponder()
     }

Any help is greatly appreciated.

first try checking if the “touchesBegan” function really is being called. try putting a print statement and print anything just to see if it prints out then you want to hide your keyboard

I don’t have the touchesBegan function in my code. Do I need to add it? I thought it is activated when the screen is touched?

yes because thats the code that get fired when you touch the screen, hideKeyboard in this case is just a function so basically you can even just do “efficiency.resignFirstResponder()” inside the touchesBegan