Josh R Josh R - 7 months ago 23
Swift Question

how to retrieve text from a textbox that was created programmatically in swift 2.0?

I am trying to take the text from multiple text fields that are added programmatically as the user needs them by pressing a button and add it to an array to use on the next view controller when press the submit button however I cant figure out how to do it. This is my code for how I create the text fields when the button is pressed.

var numberOfTasks = 1

var i = 0

@IBAction func addTaskButton(sender: AnyObject)
numberOfTasks = numberOfTasks + 1



override func viewDidLoad() {
scrollViewTAR.contentSize.height = 50

func addNewTask(){

var yPosition:CGFloat = 10
var xPosition:CGFloat = 0
var textWidth:CGFloat = scrollViewTAR.frame.width-20

for (i=0; i<numberOfTasks; i = i + 1){

var textField: UITextField = UITextField()
textField.frame = CGRectMake(xPosition, yPosition, textWidth, 30)
textField.placeholder = "Enter Task \(i + 1) Here"
textField.font = UIFont.systemFontOfSize(15)
textField.borderStyle = UITextBorderStyle.RoundedRect
textField.autocorrectionType = UITextAutocorrectionType.No
textField.keyboardType = UIKeyboardType.Default
textField.returnKeyType = UIReturnKeyType.Done
textField.clearButtonMode = UITextFieldViewMode.WhileEditing;

scrollViewTAR.frame.size.width = view.frame.width-20 =
scrollViewTAR.contentSize.height += 20
yPosition += 35


If you need any of my other code just ask.


The issue you are running into is one of scoping. When you declare

var textField: UITextField = UITextField()

That means that this texfield is scoped only within this function

So you have a few options

1) change your function to:

func addNewTask() -> UITextField

and have it return textField

2) make textField a class level construct

var textfield: UITextField?
func addNewTask() {

// lots of code

self.textField = UITextField()

In either case, however, when you are accessing the value of the text you refer to the

.text property

enter image description here

And you can simply do this by:

textField.text = "HELLO"