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

↘锁芯ラ 提交于 2021-02-07 07:27:48

问题


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?


回答1:


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 :

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.




回答2:


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);
}


来源:https://stackoverflow.com/questions/33967735/get-uitextfield-from-uiview-using-an-identifier-tag-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!