0

Here is the objects hierarchy in my ViewController in Main.Storyboard

all objects

Button same size with superview. I would like to close the keyboard with the button click action that's why I wrote this code scope:

@IBAction func btnCloseKeyboardClick(_ sender: UIButton) {
    print("A")
    for viewItem in self.view.subviews
    {
        print("B")
        if (viewItem is UITextField)
        {
            print("C")
            let tField = viewItem as! UITextField
            tField.resignFirstResponder()
        }
    }
}

but it does not close the keyboard means I don't see print("C")

I solved this problem like in this link but I would like to ask above situation also

faris97
  • 402
  • 4
  • 24
mannyCalavera
  • 593
  • 1
  • 4
  • 23

1 Answers1

1

If you only have one textfield in your view and want to dismiss keyboard for that, the simple way is to call view.endEditing(true) in your button action

Mac3n
  • 4,189
  • 3
  • 16
  • 29
  • My friend Thanks but Let's assume I have at least 2 textfield objects in my page. That's why I wrote the 'for scope' in button action. I can write your code but first I need to see print("C") code line. This is the problem. @Mac3n – mannyCalavera Feb 06 '20 at 09:02
  • for dismiss the keyboard in this way you don't need to check for the view class type, just in your IBAction method call `view.endEditing(true)` below print("A") – Mac3n Feb 06 '20 at 09:05
  • it works after I remove if (viewItem is UITextField) like you say. But How can I check the viewItem is UITextField or not? Is this checking not necessary? – mannyCalavera Feb 06 '20 at 09:14
  • 1
    if the purpose of action is dismiss the keyboard from view, it’s not necessary to check view type because endEditing method belongs to view not textfield – Mac3n Feb 06 '20 at 09:19