Search code examples
iosswiftuiviewuitextfield

Get UITextField from UIView using an Identifier/Tag (SWIFT)


I need to know how I can access a particular UITextField within a UIView from the ViewController class.

The setup I have currently is that I have ViewController that is linked to a View in Storyboard. I have UIView in nib that has 3 UITextFields. I load the view up using the following code:

TextFieldView = UINib(nibName: "TextView", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! UIView
self.view.addSubview(TextFieldView)

I can get all three UITextField and their values using the following code:

for case let textField as UITextField in TextView!.subviews {
    print(textField.text)
}

My issue is that how can I get the value of any one particular UITextField using some sort of identifier or a tag. Lets say I have 3 UITextFields named TextField1, TextField2, and TextField3 respectively. How do I get the value of TextField2?


Solution

  • If you want to find it by class then you can loop like as :

    for view in self.view.subviews {
        if let textField = view as? UITextField {
            print(textField.text!)
        }
    }
    

    If you want to find through tag then you can use viewWithTag as described by @BalajiKondalrayal.

    Set tag of text field as follows :

    enter image description here

    Select text field and set tag property.

    @IBAction func getAllTextFromTextFields(sender: AnyObject) {
        //Get All Values
        for view in self.view.subviews {
            if let textField = view as? UITextField {
                print(textField.text!)
            }
        }
        //Get One By One with Tag
        if let txtField1 = self.view.viewWithTag(1) as? UITextField {
            print(txtField1.text!)
        }
    
    }
    

    Hope it help you.