使用标识符/标签(SWIFT)从UIView获取UITextField [英] Get UITextField from UIView using an Identifier/Tag (SWIFT)
问题描述
我需要知道如何从ViewController类访问UIView中的特定UITextField.
I need to know how I can access a particular UITextField within a UIView from the ViewController class.
我目前的设置是我有一个链接到情节提要中的View的ViewController.我在笔尖中有3个UITextFields的UIView.我使用以下代码加载视图:
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)
我可以使用以下代码获取所有三个UITextField及其值:
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)
}
我的问题是,如何使用某种标识符或标签来获取任何一个特定UITextField的值.可以说我有3个分别名为TextField1,TextField2和TextField3的UITextField.如何获取TextField2的值?
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?
推荐答案
如果要按类查找它,则可以像这样循环:
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!)
}
}
如果要查找标记,则可以使用@BalajiKondalrayal所述的 viewWithTag
.
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.
这篇关于使用标识符/标签(SWIFT)从UIView获取UITextField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!