简体   繁体   中英

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

在此处输入图片说明

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

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"

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM