Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing text of Swift UILabel

I am attempting to learn Apple's Swift. I was recently trying to build a GUI app, but I have a question:

How do I interact with GUI elements of my app? For instance, I used interface builder to make a UILabel, and I connected it to my viewcontroller by control-clicking, so that I get the @IBOUTLET thing. Now, how do I, while in my view controller, edit the text of this UILabel? To state it another way, what code can I use to programatically control the text of something on my storyboard? All methods I have found online only appear to work with a button generated in code, not a button generated on a storyboard.

I've seen code like

self.simpleLabel.text = "message" 

If this is right, how do I link it with the label in question? In other words, how do I adapt this code to be connected with the IBOutlet (If that's what I do)

like image 888
rocket101 Avatar asked Jul 30 '14 17:07

rocket101


People also ask

How do I change the UILabel text in Swift?

To change the font or the size of a UILabel in a Storyboard or . XIB file, open it in the interface builder. Select the label and then open up the Attribute Inspector (CMD + Option + 5). Select the button on the font box and then you can change your text size or font.

How do I change the text of a button in Swift?

You can omit UIControlState part and just write like button. setTitle("my text here", forState: . Normal) .


2 Answers

If you've successfully linked the control with an IBOutlet on your UIViewController class, then the property is added to it and you would simply replace simpleLabel with whatever you named your IBOutlet connection to be like so:

class MyViewController: UIViewController {     @IBOutlet weak var myLabel: UILabel!     func someFunction() {         self.myLabel.text = "text"      } } 
like image 107
Alex Zielenski Avatar answered Oct 04 '22 15:10

Alex Zielenski


The outlet you created must've been named by you. The outlet belongs to your view controller. self.simpleLabel means 'fetch the value of my property named 'simpleLabel'.

Since different outlets have different names, using self.simpleLabel here won't work until your outlet is named 'simpleLabel'. Try replacing 'simpleLabel' with the name you gave to the outlet when you created it.

The correct way now would be:

self.yourLabelName.text = "message" 
like image 27
duci9y Avatar answered Oct 04 '22 15:10

duci9y