Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 872
Bhavik P. Avatar asked Nov 28 '15 04:11

Bhavik P.


2 Answers

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.

like image 109
Ashish Kakkad Avatar answered Nov 15 '22 04:11

Ashish Kakkad


Use viewWithTag option. Try this:

if let theTextField = self.view.viewWithTag(yourTagId) as? UITextField {
        print(theTextField.text)
    }

Objective-C :

UIView *view = [self.view.viewWithTag:YourTagId];

if([view isKindOfClass:[UITextField class]]
{ NSLog(@"%@", view.text);
}
like image 35
Balaji Kondalrayal Avatar answered Nov 15 '22 04:11

Balaji Kondalrayal