Donny P Donny P - 1 year ago 77
Swift Question

Input from UITextField connected from storyboard to Swift view controller file

Using Swift, how do I get the input from a


In my Main.storyboard, I have chosen a "Text Field" from the premade components and dragged it onto my storyboard.

Now how can I access its value in my ViewController.swift?

What I'm currently doing:

I ctrl+drag the text field into my ViewController.swift file. Then in the popup-box I choose "outlet" and name it "myInput".

Then in another function, I access its value by using

Is this the only way to access its input? Is my approach following Swift conventions?


Yes, your approach of creating an IBOutlet from the storyboard and referencing it using self.myInput.text is a standard way of accessing this field in Swift.

As for whether to use self.myInput vs. myInput, I prefer to always write self because it is very obvious that the variable is a property and will probably be changed in many different places (opposed to a local var). Also, once you have self there, you don't have to worry about introducing local vars with the same name or making changes if you copy and paste a block of code into a closure that requires self.