I'm trying to change the text on a label in a simple iOS app.
The idea is to write a message in a textField and have it change the label once I press a button.
the objective-c code states the following:
[self.simpleLabel setText:message]
simpleLabel: is associated with the UILabel
setText:
is the method
message: is a variable set in a previous line
How would I write this in swift?
I tried combing through the Apple documentation but came up with nothing.
Open your storyboard and view controller source side by side in the assistant editor. Then select the label. Switch to the connections inspector and then drag from the small circle next to "New Referencing Outlet" and into the view controller source file. This should create the @IBOutlet for you.
Swift uses the same cocoa-touch API. You can call all the same methods, but they will use Swift's syntax. In this example you can do something like this:
self.simpleLabel.text = "message"
Note the setText method isn't available. Setting the label's text with = will automatically call the setter in swift.
swift solution
yourlabel.text = yourvariable
or self is use for when you are in async {brackets} or in some Extension
DispatchQueue.main.async{
self.yourlabel.text = "typestring"
}
use a simple formula: WHO.WHAT = VALUE
where,
WHO is the element in the storyboard you want to make changes to for eg. label
WHAT is the property of that element you wish to change for eg. text
VALUE is the change that you wish to be displayed
for eg. if I want to change the text from story text to You see a fork in the road in the label as shown in screenshot 1
In this case, our WHO is the label (element in the storyboard), WHAT is the text (property of element) and VALUE will be You see a fork in the road
so our final code will be as follows: Final code
screenshot 1 changes to screenshot 2 once the above code is executed.
I hope this solution helps you solve your issue. Thank you!
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