Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input from UITextField connected from storyboard to Swift view controller file

Using Swift, how do I get the input from a UITextField?

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 self.myInput.text.

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

like image 995
Don P Avatar asked Dec 13 '14 00:12

Don P


People also ask

Can you combine swift UI with storyboard?

The answer is YES! Here we will be discussing a simple way to use SwiftUI into our existing project, which already consists of a storyboard. Let's dive in then!

How do I connect ViewController Swift to ViewController in storyboard?

Create a new IBOutlet called shakeButton for your storyboard button in your ViewController. swift file. Select the shake button in Interface Builder. Then hold down the control button ( ⌃ ) and click-drag from the storyboard button into your ViewController.

What is Uitextfield in Swift?

An object that displays an editable text area in your interface.


1 Answers

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.

like image 85
Hayley Guillou Avatar answered Oct 19 '22 18:10

Hayley Guillou