Reputation: 25
Iam adding textFields with this code to add 3 UITextFields to ViewController:
for var index = 0; index < 3; ++index {
var textField = UITextField(frame: CGRectMake(0, 0, 300, 40))
var pom:CGFloat = 130 + CGFloat(index*50)
textField.center = CGPointMake(185, pom)
textField.layer.borderWidth = 1.0;
textField.layer.cornerRadius = 5.0;
textField.textAlignment = NSTextAlignment.Center
self.view.addSubview(textField)
}
and now i need to get text from all textFields. Can someone tell me, how can i make it?
Upvotes: 1
Views: 2124
Reputation: 2782
You could store them in an array, set the tag
property on each one with the value of the counter in your loop, then retrieve them by that tag later on:
class MyViewController: UIViewController {
var textFields = [UITextField]()
override func viewDidLoad() {
super.viewDidLoad()
for var index = 0; index < 3; ++index {
var textField = UITextField(frame: CGRectMake(0, 0, 300, 40))
var pom:CGFloat = 130 + CGFloat(index*50)
textField.center = CGPointMake(185, pom)
textField.layer.borderWidth = 1.0;
textField.layer.cornerRadius = 5.0;
textField.textAlignment = NSTextAlignment.Center
textField.tag = index
self.textFields.append( textField )
self.view.addSubview(textField)
}
for var index = 0; index < 3; ++index {
if let textField = self.textFieldForTag( index ) {
print( textField.text )
}
}
}
func textFieldForTag( tag: Int ) -> UITextField? {
return self.textFields.filter({ $0.tag == tag }).first
}
}
Upvotes: 1