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?
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!
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.
An object that displays an editable text area in your interface.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With