Home > Blockchain >  Setting a label to a value in Swift on XCode?
Setting a label to a value in Swift on XCode?

Time:10-25

I understand it’s rather basic, but I’m only trying to get a grasp on basic functions.

I have produced some code by partially my own knowledge and partial bits from different guides.

I am not getting any errors, but the label is not displaying itself as “Text”. I believe it’s to do with the order/place my code is put.

Please help explain how I can fix this!

Please note as well:

  • I have just a single label called myLabel (named under the document section of my the identity inspector
  • It is has the text “Loaded” put into it already when I put it in.
  • I have no other code anywhere, only the default new project code.
  • I renamed the ViewController to ViewManager to avoid a class error.

First image: This is the image just so you know the location and other bits. I’ll attach the code too:

Second image: What I get, with no errors:

Third image: My main storyboard file:

And now it in code:

import UIKit

class ViewController: UIViewController {
   @IBOutlet weak var myLabel: UILabel!
   @IBAction func labelSet() {
       myLabel.text = "Text"
    }
  }

CodePudding user response:

  1. Make sure that the IBAction is connected to Touch Up Inside in Interface Builder.

  2. Change the signature of the IBAction to

    @IBAction func labelSet(_ sender: UIButton) {
    

CodePudding user response:

Your function func labelSet() isn't called anywhere. Neither in the Storyboard nor elsewhere.

You can call it in viewDidLoad() like this:

    override func viewDidLoad() {
        super.viewDidLoad()
        labelSet()
    }

Alternatively call it after the label has loaded.

    @IBOutlet weak var myLabel: UILabel! {
        didSet {
            labelSet()
        }
    }
  • Related