Changing text of Swift UILabel

rocket101 picture rocket101 · Jul 30, 2014 · Viewed 66.3k times · Source

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)

Answer

Alex Zielenski picture Alex Zielenski · Jul 30, 2014

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" 
    }
}