Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I change text in a label with swift?

Tags:

uilabel

swift

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.

like image 596
StevieKnox Avatar asked Jun 18 '14 01:06

StevieKnox


People also ask

How do I change the label text on a button click in Swift?

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.


3 Answers

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.

like image 76
Connor Avatar answered Sep 29 '22 06:09

Connor


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"
}
like image 37
Shakeel Ahmed Avatar answered Sep 29 '22 07:09

Shakeel Ahmed


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!

like image 33
Aditya Vyavahare Avatar answered Sep 29 '22 08:09

Aditya Vyavahare