JPC
JPC

Reputation: 5173

How to change text UILabel in swift code?

I'm new to swift and I am trying to understand UILabel text property

Based on what I have read, my understanding is that I can replace text with any String . So I did

enter image description here

The text property is "read-only" , is there a way I can change text label by hardcoding in swift ?

Upvotes: 0

Views: 2449

Answers (3)

Edison
Edison

Reputation: 11987

100% programatically would be like this. This both creates the label and the string.

override func viewDidLoad()
{
super.viewDidLoad()
var label = UILabel(frame: CGRectMake(0, 0, 200, 21))
label.center = CGPointMake(160, 284)
label.textAlignment = NSTextAlignment.Center
label.text = "Burger"
self.view.addSubview(label)
}  

Upvotes: 1

ReggieY
ReggieY

Reputation: 25

I am not in front of my computer to verify this, but I don't think you need to mark it as "self"

Just Food.text = "Burger"

Additionally. It is common for you to put variables with the first letter as lower case with each other words first letter being upper case

For example.

var firstWord = "Traditionally the best way to code"

Capital first letter first word is traditionally used for classes.

Example

Class NewClass = "Blah Blah"

Upvotes: 2

schrismartin
schrismartin

Reputation: 459

You cannot set a value like this in the declaration section of the class.

Since you're working with a UIViewController, you'll want to go to the viewDidLoad() method and put self.Food.text = "Burger" there.

For example:

import UIKit

class TestViewController: UIViewController {

    @IBOutlet weak var Food: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.Food.text = "Burger"
    }
}

The viewDidLoad() method is called by the system when (coincidentally enough) the view is first loaded. After the view has loaded, you are free to make any edits to any of the objects on the screen. viewDidLoad will be where you will want to perform the majority of the setting up of your view.

Upvotes: 1

Related Questions