skip to Main Content

My Swift app required the user to enter decimal values on a UITextfield. The Decimal Pad appears when the user click inside the textfield. Then the user enter the amount and click the Calculate Button to see results.

I want to close the Decimal Pad when the user click outside the de UITextfield or outside the keyboard.

My App looks like this:
My App

This is my first app in Swift (Xcode). So I’m newbie. Please try to recommend a code.

I am doing something wrong. 🙁

The error

3

Answers


  1. Chosen as BEST ANSWER

    Solution is:

    1- Create a Tab Gesture Recognizer from the object library (+) to the main View.

    2- Create an @IBAction connection in the functions area of the program. This step automatically creates this.

    @IBAction func dismissKeyboard(_ sender: Any) {
    }
    

    3- Add a blank line in that function to include this line:

    @IBAction func dismissKeyboard(_ sender: Any) {
        self.view.endEditing(true)  // The added line
        }
    

  2. as comment given by: cristian_064

    step: 1 – create IBOutlet of the UIView

    @IBOutlet weak var vwParent: UIView!
    

    step: 2 – assign tap gesture to UIView

    let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
    vwParent.addGestureRecognizer(tap)
    

    step: 2 – create an event handler(@objc) method for handling the operation when UIView is tapped.

    @objc func handleTap(_ sender: UITapGestureRecognizer? = nil) {
       self.view.endEditing(true)
    }
    
    Login or Signup to reply.
  3. Just use the IQKeyboardManager library, it will solve all your keyboard problems. A "Close" button will appear above the keyboard, a tap outside the keyboard to hide will also work in any controller without additional settings

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search