Search code examples
iosswiftuitextfieldtextfieldsubview

How can I reach UITextfield in subviews in Swift?


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


Solution

  • 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