how do I change text in a label with swift?
Asked Answered
E

3

47

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.

Elegize answered 18/6, 2014 at 1:12 Comment(1)
E
92

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.

Equine answered 18/6, 2014 at 1:19 Comment(3)
I tried similar combinations but none of them worked. thanks!Elegize
Where do I specify the label ID "simpleLabel"?Linkage
simpleLabel is the name he used in his example. Use whatever variable you have for your label in place of itEquine
H
18

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"
}
Harass answered 2/3, 2017 at 10:15 Comment(0)
L
2

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!

Lesterlesya answered 18/11, 2020 at 10:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.